Home > OS >  Concatenate the values of a list after inputting multiple column / row raw input in python
Concatenate the values of a list after inputting multiple column / row raw input in python

Time:12-24

I'm trying to use a program in here to convert a copy and pasted list from excel into a list that I can manipulate using concatenate in Python. When I input the multiple column / row values I get a list that I'm having trouble manipulating. See the below example:

  • the program is below:
def detail_input():
     try:
        while True:
            data=raw_input()
            if not data: break
            yield data
     except KeyboardInterrupt:
        return
  • the raw input is copied from excel onto a unix command line:

123 56
321 42
987 24

  • I then get a return that looks like this:
userInput = list(detail_input())

[['123\t56'],['321\t42'],['987\t24']]

  • My desired output would look like this:

the group is 123 and their profile is 56
the group is 321 and their profile is 42
the group is 987 and their profile is 24

I've tried to use the below to remove the tab delimiter:

values = list(csv.reader(userInput, delimiter='\t'))
  • but it converts the list into a tuple and I can't extract the individual values - I can only extract both values inside of each bracket :\

[['123','56'],['321','42'],['987','24']]

Please help if you have any ideas

CodePudding user response:

you can do this.

values = list(csv.reader(userInput, delimiter='\t'))
# add the following line to print what you need.
[print("the group is {} and their profile is {}".format(each[0], each[1])) for each in values]

or something as easy as following.

values = list(csv.reader(userInput, delimiter='\t'))

for each in values:
    group = each[0]
    profile = each[1]
    print("the group is {} and their profile is {}".format(group,profile))

CodePudding user response:

If the format is stable (always something like \d \t\d , so a number, followed by tab and then another number) you could do something like this

values = {sub_list[0].split('\t')[0]: sub_list[0].split('\t')[1] for sub_list in userInput}

to get a dictionary

then something like

for key, value in values.items():
    print(f'the group is {key} and their profile is {value}')

But this approach is not a good one to start with, and you would probably better served by exporting a csv or tsv file from excel and using the csv library to read the data.

  • Related