我有一个有序字典,其中包含同一个键的多个值。我需要遍历项目并对每个值执行不同的操作。
该词典如下: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.
答案 0 :(得分:1)
您只需要1个循环即可提取所有数据。只需使用iteritems()
并解压缩值元组即可获得所需的字符串
for each_key, (each_file, each_substr) in d.iteritems():
print each_key, each_file, each_substr
答案 1 :(得分:0)
我想出来了。
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!!!
"对于each.key,(each_file,each_substr)在d.iteritems()中:"如果我们不知道预期会有多少项目,那就不是非常有效了[