简体   繁体   中英

How do I append a matching element from a list to another list?

I have two lists: file_name = ['AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg', 'AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg', 'CJ19+244082+ Primary.jpg']

number = ['775002', '200998', '244082']

I'm trying to append to the list number the matching string that I find in the list file_name so that it becomes:

number = [['775002', 'AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg'], ['200998', 'AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg'], ['244082', 'CJ19+244082+ Primary.jpg']]

These lists are extracted from singular column.csv files, so I am also looking to export it in a format readable on Excel to work in a database.

This is what I have so far:


with open('file_name.csv', newline='') as csvfile:
    file_name = list(csv.reader(csvfile))

with open('number.csv', newline='') as csvfile:
    number = list(csv.reader(csvfile))

for i in number:
    matching = [s for s in file_name if number[i] in s]
    number[i].append(matching)```

You could store everything in a dict

with open('file_name.csv', newline='') as csvfile:
   file_names = [line.split()[0] for line in csvfile]

with open('number.csv', newline='') as csvfile:
   numbers = [line.split()[0] for line in csvfile]

newdict = {}

for file_name in file_names:
    for number in numbers:
        if not number in newdict:
            newdict[number] = []
        if number in file_name:
            newdict[number].append(file_name)

output:

{'775002': ['AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg'], '200998': ['AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg'], '244082': ['CJ19+244082+ Primary.jpg']}

The issue is you're altering a list while iterating it. Never a good idea plus you're accessing number[i] as if you were iterating with a range. This can be easily done using a comprehension too though

file_name = ['AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg', 'AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg', 'CJ19+244082+ Primary.jpg']
number = ['775002', '200998', '244082']

all_matches = [[i] + [s for s in file_name if i in s] for i in number]

[['775002', 'AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg'], ['200998', 'AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg'], ['244082', 'CJ19+244082+ Primary.jpg']]

Or to use a more appropriate data type ( dict )

all_matches = {i: [s for s in file_name if i in s] for i in number}

{'775002': ['AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg'], '200998': ['AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg'], '244082': ['CJ19+244082+ Primary.jpg']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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