简体   繁体   中英

Comparing Lists elements and sets in python

First I'll show my code and then I'll explain:

for eachfile in matches:
    if eachfile in set1:
        print 'find one match'
        shutil.copy2(eachfile, '/Users/r2-d2/Desktop/folder')
        print 'copy done'

matches is a list like this:

[fooFILE_Aspam.txt, barFILE_B.CSV, codeFILE_Cdog.vcf]

set1 is a set like which looks like this:

(FILE_A, FILE_B, FILE_F...)

I'm iterating over the list to check if inside each entry there's any of the elements of the set. If it does I copy the entry away. In the above example scenario I expect a match for FILE_A and FILE_B . I know that the keyword in would work the other way around but I can't find an elegant solution without using another loop.

Set1 is not a set (like you stated) but a tuple, so you need to cast and then you can use a set intersection to filter duplicates across both

 matching_files = list(set(matches).intersection(set(set1)))

 for file in matching_files:
     # Do your copy
     pass

集合之间的交集如何?然后复制结果?不确定是否要在字符串中查找数学,即列表中的元素是否与集合中的元素“相同”

There are many ways to do this.

import re
pat = re.compile('|'.join(set1))
for match in matches:
    if pat.search(match):
        # do stuff

But I would probably introduce the filter with the help of regex (or possibly fnmatch ) while calculating matches

use any to check if any matches eachfile.

matches = ['fooFILE_Aspam.txt', 'barFILE_B.CSV', 'codeFILE_Cdog.vcf']
set1 = ('FILE_A', 'FILE_B', 'FILE_F')

for eachfile in matches:
    if any([x in eachfile for x in set1]):
        print eachfile

First, in operator applies to both set and str . In the former case, you are checking for exact string match; in the second, for contiguous substring inclusion. I assume you are after the latter, so this should work.

matches = ['fooFILE_Aspam.txt', 'barFILE_B.CSV', 'codeFILE_Cdog.vcf']
set1 = {'FILE_A', 'FILE_B', 'FILE_F'}

to_move = [fname for fname in matches if any(t in fname for t in set1)]

# In [39]: q.to_move
# Out[39]: ['fooFILE_Aspam.txt', 'barFILE_B.CSV']

You can use this:

for eachfile in [x for x in matches if x in set1]:
    print 'find one match'
    shutil.copy2(eachfile, '/Users/r2-d2/Desktop/folder')
    print 'copy done'

Or, do it inside the for loop - list:

def shCopy(file,dest='/Users/r2-d2/Desktop/folder'):
    print 'find one match'
    shutil.copy2(file, dest)
    print 'copy done'

[shCopy(x) for x in matches if x in set1]

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