简体   繁体   English

list 打印出多个元素而不是 2 个

[英]list printing out multiple elements instead of just 2

having a small issue where, using the code below, when printing out strings in a list, having more than 2 will cause there to be double the strings I printed.有一个小问题,使用下面的代码打印列表中的字符串时,超过 2 个将导致我打印的字符串翻倍。

    print("Geneaology for: \n\t" + user_name + "\t\t" + user_birthday)
    print("Parents: ")
    # Prints out parents names and date of birth
    for x in parent_names:
        for y in parent_birthdays:
            print(str("\t" + x + "\t\t" + y))
    # Prints out siblngs names and date of birth
    print("Siblings: ")
    for x in sibling_names:
        for y in sibling_birthdays:
            print(str("\t" + x + "\t\t" + y))
    # Prints out grandparents names and date of birth
    print("Grandparents: ")
    for x in grandparent_names:
        for y in grandparent_birthdays:
            print(str("\t" + x + "\t\t" + y))

With the "parent_name" and "parent_birthday" lists having only 1 string, I get this:由于“parent_name”和“parent_birthday”列表只有 1 个字符串,我得到了这个:

Geneaology for: 
        jm              01/01/01
Parents:
        aa              01/01/01

With 2 strings in each, i get this:每个有 2 个字符串,我得到这个:

Geneaology for: 
        jm              01/01/01
Parents:
        aa              01/01/01
        aa              02/02/02
        bb              01/01/01
        bb              02/02/02

I haven't tried all to much, other than changing the positioning of certain things and variables, so any help is appreciated.除了更改某些事物和变量的定位之外,我还没有尝试太多,因此感谢您提供任何帮助。

The problem here is that parent_names and parent_birthdays are parallel lists.这里的问题是parent_namesparent_birthdays是并行列表。 You should be storing this in a single list, where each entry is a dictionary with the data for that one person.您应该将其存储在一个列表中,其中每个条目都是一个包含该人数据的字典。 You CAN do what you want like this, but you really need to reorganize your data.你可以像这样做你想做的事,但你真的需要重新组织你的数据。

    for x,y in zip(parent_names, parent_birthdays):
        print("\t" + x + "\t\t" + y)

And it's silly to call the str() function on something that's already a string.在已经是字符串的东西上调用str()函数是愚蠢的。

Would you consider to make Parents a dictionary?你会考虑让父母成为一本字典吗?

parent = {
  "name": "aa",
  "birthday": "01/01/1995"
}

Then:然后:

# Where "parents" is a list of parent dictionaries
for parent in parents:
  print("\t" + parent['name'] + "\t\t" + parent['birthday'])

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

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