简体   繁体   English

以这种特定格式打印嵌套列表

[英]Printing nested list in this specific format

I am going through automate the boring stuff, diong chapter 6 first practice problems:我正在通过自动化无聊的东西,第 6 章第一次练习问题:

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. 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 |苹果| 高分辨率照片| CLIPARTO Alice |爱丽丝 | dogs小狗

oranges|橘子| Bob |鲍勃 | cats

cherries |樱桃| Carol |卡罗尔 | moose驼鹿

banana |香蕉| 高分辨率照片| CLIPARTO 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??这确实给了我预期的output,但是我使用的范围参数感觉有点野蛮,所以有没有其他方法可以解决这个问题?

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您可以根据索引将每个值存储在 hash 表(字典)中,然后一起打印结果或相应的索引值

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 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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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