Yas*_*tha 3 python arrays list python-2.7
我有一个使用创建的文件名列表dirs = os.listdir(dir/path).
我也从csv文件导出数据集. stocks = csv.reader(open('config.csv', 'rb'))
样本库存数据:
FILENAME1,URL1
文件名2,URL2
我需要做的是dirs在python脚本中获取列表中每个文件的每个url .提前致谢.
Pytho为此提供了一个内置函数zip:
for dir, stock, in zip(dirs, stocks)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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
Run Code Online (Sandbox Code Playgroud)
看,这不难,对吗?Python让我们的生活更轻松!:)
替代方案:如果性能非常重要,请使用itertools.izip.
更新
原来上面的答案不是OP所要求的.嗯,和史蒂夫一样,我会用一本字典:
stock_dict = dict(stock)
urls = [stock_dict.get(file, "Not found") for file in dirs]
Run Code Online (Sandbox Code Playgroud)
演示:
我们假设目录中有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']
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |