Home > database >  Print out a list of people with same birth year in python
Print out a list of people with same birth year in python

Time:04-13

I have different lists with names and year birth as below:

list 1: [ 'John', '1991', 'male']
list 2: [ 'Mac', '1992', 'male']
list 3: [ 'Ria', '1991', 'female']

And I want to print in python as :

Born in 1991:
John, male
Ria, female
Born in 1992:
Mac, male

CodePudding user response:

You can construct temporary dictionary where key is year and values are lists of (name, sex) and use this dictionary to print the desired output:

list_1 = ["John", "1991", "male"]
list_2 = ["Mac", "1992", "male"]
list_3 = ["Ria", "1991", "female"]

tmp = {}
for l in (list_1, list_2, list_3):
    name, year, sex = l
    tmp.setdefault(year, []).append((name, sex))

for k in tmp:
    print("Born in {}:".format(k))
    for v in tmp[k]:
        print(", ".join(v))

Prints:

Born in 1991:
John, male
Ria, female
Born in 1992:
Mac, male

CodePudding user response:

You could try this:

import pandas as pd

elements = []
for index in range(0,len(list_1)):
    item_in_list_1 = list_1[index]
    item_in_list_2 = list_2[index]
    item_in_list_3 = list_3[index]
    
    elements.append([item_in_list_1,item_in_list_2,item_in_list_3])
    
df = pd.DataFrame({'names':elements[0],
            'year':elements[1],
             'gender':elements[2]})

#If you want to print the cases where year is 1991, try this:
df2 = df[df['year'] == '1991']
for index in range(0, len(df2)):
    print(f"{df2.iloc[index]['names']} born in {str(df2.iloc[index]['year'])} and its gender is {df2.iloc[index]['gender']}")

CodePudding user response:

If you can store your lists in a single "outer" list, and if you are okay with using the pandas library, you can use its DataFrame class and groupby method:

import pandas as pd

data = [
    ["John", "1991", "male"],
    ["Mac", "1992", "male"],
    ["Ria", "1991", "female"],
]

df = pd.DataFrame(data, columns=["name", "year", "gender"])

for year, sub_df in df.groupby("year"):
    print(f"Born in {year}:")
    for row in sub_df.itertuples():
        print(f"{row.name}, {row.gender}")

The above code will give the following output:

Born in 1991:
John, male
Ria, female
Born in 1992:
Mac, male
  • Related