简体   繁体   中英

For loop into a set python

I am attempting to create a set based on the name of the files that I am reading.

Code:

ext = '*.xml'
directory = './'
sets = {}

    for file in glob.glob1(directory,ext):
        print(sets)

Output

pom copy.xml
pom copy 3.xml
pom copy 2.xml
pom copy 5.xml
pom.xml
pom copy 4.xml
pom copy 6.xml
pom copy 7.xml
pom copy 9.xml
pom copy 8.xml
pom copy 10.xml

Expected output

{pom copy.xml, pom copy 3.xml, pom copy 2.xml, pom copy 5.xml, pom.xml, pom copy 4.xml, pom copy 6.xml, pom copy 7.xml, pom copy 9.xml, pom copy 8.xml, pom copy 10.xml}

Any help would be appreciated.

Here is how you can simply wrap your glob.glob function call with set() :

import glob
ext = '*.txt'
directory = './'
sets = set(glob.glob(directory+ext)) # Using a comma with give you an error, you need to use a `+`

Just append each file to Your set:

import glob
ext = '*.xml'
directory = './'
sets = set()

for file in glob.glob(directory+ext):
    sets.add(file)

One thing is worth notice:

[] = empty list

() = empty tuple

{} = empty dict

There's no literal syntax for the empty set. You have to write set() instead of {} .

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