简体   繁体   中英

Printing nested list in this specific format

I am going through automate the boring stuff, diong chapter 6 first practice problems:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

I would like to tried the following output without using zip function or map cause I am forcing myself to get deeper understanding regarding list manipulation without using those methods.

apples | Alice | dogs

oranges| Bob | cats

cherries | Carol | moose

banana | David | goose

So far I have tried the following:

for i in range(len(tableData[0])):
    print(' '.join(subLst[i] for subLst in tableData))

which does give me intended output, but the range parameter I used feels kinda brutish, so is there any other way I could solve this problem??

you can store the each value according to the index in a hash table (dictionary) and then print the result or corresponding index values together

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]
         
dic = {}
for sublist in tableData:
    for i, v in enumerate(sublist):
        if i not in dic:
            dic[i]=[v]
        else:
            dic[i].append(v)
            

for k, v in dic.items():
    print(" | ".join(v))

output

apples | Alice | dogs
oranges | Bob | cats
cherries | Carol | moose
banana | David | goose

NOTE: This consider the lenght of sublist is same, if length is different then index value for that index will be shown but not able to know the value belong to which sublist index, to solve that first one need to make all sublist of same length and then proced with this code.

You could use list comprehension:

[[row[i] for row in tableData] for i in range(len(tableData[0]))]

[['apples', 'Alice', 'dogs'],
 ['oranges', 'Bob', 'cats'],
 ['cherries', 'Carol', 'moose'],
 ['banana', 'David', 'goose']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM