繁体   English   中英

遍历有序字典python的多个值(针对同一键)

[英]iterating through multiple values [for the same key] of an ordered dictionary python

我有一个有序的字典,其中同一键有多个值。 我需要遍历所有项目,并对每个值执行不同的操作。

该字典如下:

OrderedDict([('1', ['file a','file1','file2','file3', 'Substringb']), ('2', ['file c', 'Substringd']), ('3', ['filed', 'Substringe']),('4', ['file f', 'Substringg']), ('5', ['file h', 'Substringi'])]

每个项目都有文件路径和一个子字符串。 我无法控制从其他功能接收多少文件。 我想打开它们中的每一个并寻找子字符串。 现在,当我执行以下操作时,我得到的值太多,无法解压缩:

下面是我使用的代码:当我提取值并尝试遍历each_file时,它不起作用-打印每个文件只会打印文件路径的第一个字符[ex:'C',而文件路径为“'C: \\ Users \\ xxxxxx \\ Documents \\ something.txt“]。 请帮助我解决这个问题。 TIA。

for each_key, (each_file, each_substr) in d.iteritems():  #Giving too many values to unpack error since there are multiple files coming in[no control on how many to expect] 
    for each in each_file:
       print each
       with open(each_file) as f: ## This is giving error as the each is not working as I would expect it to.

您只需要1个循环即可提取所有数据。 只需使用iteritems()并解压值元组即可获取所需的字符串

for each_key, (each_file, each_substr) in d.iteritems():
    print each_key, each_file, each_substr

我知道了。

for each_key, each_value in d.iteritems():   
each_substring = each_value[1] #Since my substring is appended at the end and am removing it from the each_values list in the below step after saving it here
each_file = each_value[:-1] #Grabbing all files except the last one
for each in each_file:
   print each
   with open(each_file) as f: ## Now this works!!! 

“对于d.iteritems()中的each_key,(每个文件,each_substr):”如果我们不知道要期待多少个项目,则效率不是很高[看起来就是这样]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM