Home > Back-end >  list printing out multiple elements instead of just 2
list printing out multiple elements instead of just 2

Time:10-15

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.

    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:

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

With 2 strings in each, i get this:

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.

CodePudding user response:

The problem here is that parent_names and parent_birthdays are parallel lists. 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.

CodePudding user response:

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'])
  • Related