Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate two lists in python

I am having a list of file names created using dirs = os.listdir(dir/path).

Also I am exporting a data set from a csv file. stocks = csv.reader(open('config.csv', 'rb'))

Sample stock data:

fileName1,url1

fileName2,url2

What I need to do is get the each url for each file in the dirs list in a python script. Thanks in advance.

like image 811
Yasitha Avatar asked May 19 '26 05:05

Yasitha


1 Answers

Pytho provides a built-in function for this, zip:

for dir, stock, in zip(dirs, stocks)

Demo:

>>> a = ["cat", "dogs"]
>>> b = ["http://cat-service.com", "http://dogs-care.com"]
>>> for animal, site in zip(a, b):
    print(animal, site)


cat http://cat-service.com
dogs http://dogs-care.com

See, It's not hard, right? Python makes our life easier! :)

Alternative: If performance really matters, use itertools.izip.

Update

Turns out the answer above is not what the OP was asking. Well, same as Steve, I'd use a dictionary for this:

stock_dict = dict(stock)
urls = [stock_dict.get(file, "Not found") for file in dirs]

Demo:

We assume there are 3 files in the directory, two of them are listed.

>>> stock = [("fileName1","url1"), ("fileName2","url2")]
>>> stock_dict = dict(stock)
>>> dirs = ["fileName1", "fileName2", "fileName3"]
>>> urls = [stock_dict.get(file, "Not found") for file in dirs]
>>> urls
['url1', 'url2', 'Not found']

Hope this helps!

like image 99
aIKid Avatar answered May 21 '26 23:05

aIKid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!