Python:如何从数组中的数组中提取项?

2024-04-25 20:19:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数组,其中一个是包含数组的数组

wordsEn = ["why", "because", "go"] 
wordsDe = [["warum"], ["weil", "da"], ["los", "gehen"]]

我的代码是

step = 0
size = 3
while step < size:
    word = input("Enter name of word: ")
    print("your word was " + word)
    if word in wordsEn:
       pos = wordsEn.index(word)
       print(wordsDe[pos])
       step = step + 1
    else:
        print("word not found.")

如果我要求它打印wordsDe[1],它会打印['weil', 'da']

如何使其打印为列表,如

weil da


Tags: posgosizestep数组dawordprint
3条回答

wordsDe是一个列表,列表中的3个对象是[“warum”]、[“weil”、“da”]和[“los”、“gehen”]

调用wordsDe[1]将为您提供列表中的第二个对象。。。[“好”、“大”]

如果你想打印的话

weil
da

您必须先调用wordsDe[1][0],然后再调用wordsDe[1][1]

您可以循环使用wordsDe[pos],只需逐个打印内容

step = 0
size = 3
while step < size:
    word = input("Enter name of word: ")
    print("your word was " + word)
    if word in wordsEn:
       pos = wordsEn.index(word)
       for data in wordsDe[pos]:
           print (data)
       step = step + 1
    else:
        print("word not found.")

由于列表是嵌套的,因此表示包含列表的列表。您必须根据所需的输出指定此类列表的输出格式

对于给定的情况,您可以使用以下内容:

print(*wordsDe[1], sep='\n') # First unpacks all items in the list using '*', 
                             # then tells 'print()' to separate each item using '\n'

相关问题 更多 >