gpt4 book ai didi

python - 在python中迭代两个列表

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:00 25 4
gpt4 key购买 nike

我有一个使用 dirs = os.listdir(dir/path) 创建的文件名列表。

我还从 csv 文件导出数据集。 stocks = csv.reader(open('config.csv', 'rb'))

样本股票数据:

fileName1,url1

fileName2,url2

我需要做的是在 python 脚本中获取 dirs 列表中每个文件的每个 url。提前致谢。

最佳答案

Pytho 为此提供了一个内置函数,zip :

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

演示:

>>> 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

看,这并不难,对吧? Python 让我们的生活更轻松! :)

备选方案:如果性能确实很重要,请使用itertools.izip

更新

原来上面的答案不是 OP 所问的。好吧,和史蒂夫一样,我会为此使用字典:

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

演示:

我们假设目录中有 3 个文件,列出了其中两个。

>>> 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']

希望这对您有所帮助!

关于python - 在python中迭代两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21329123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com