Home>
name_list = []
wb = openpyxl.load_workbook ("C: \ user \ name.xlsx")
ws = wb ["name"]
for row in ws.iter_rows (min_row = 2):
    values ​​= []
    for col in row:
        values.append (col.value)
    name_list.append (tuple (values))


I used openpyxl to import the above excel file.

segments = [1,2,3,6]


And after creating a list like the above, I want to display the names in the order of the numbers put in segments, and if there is no name corresponding to the entered number, I want to output the number as it is, but I can not do it well did.

Desired output
['Sato','Takahashi','Tanaka', '6']


What I tried

masters = []
for s in segments:
    if s! = name_list [0]:
        masters.append (s)
    for d in name_list:
        if s == d [0]:
            masters.append (d [1])


I wrote the above program, but it became ['1','Sato', '2','Takahashi', '3','Tanaka', '6'] and I don't know what to do. did.

  • Answer # 1

    If name_list is a list, processing is difficult, so I made it a dictionary type (name_dict).
    Also, when reading xlsxfor row in ws.iter_rows (min_row = 2):Because the first line was not read, it was selfishmin_row = 1It is said. Please put it back if necessary.

    import openpyxl
    name_dict = {}
    wb = openpyxl.load_workbook ("C: \ user \ name.xlsx")
    ws = wb ["Sheet1"]
    for row in ws.iter_rows (min_row = 1):
        values ​​= []
        for col in row:
            values.append (col.value)
        name_dict [values ​​[0]] = values ​​[1]
    print (name_dict)
    # {1:'Sato', 2:'Takahashi', 3:'Tanaka', 4:'Suzuki', 5:'Yamada'}
    masters = []
    segments = [1,2,3,6]
    for s in segments:
        if s in name_dict:
            masters.append (name_dict [s])
        else: else:
            masters.append (s)
    print (masters)
    # ['Sato','Takahashi','Tanaka', 6]