迭代排序字典的多个值[对于同一个键]

2024-04-26 12:57:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有序字典,同一个键有多个值。我需要遍历这些项,并对每个值执行不同的操作。你知道吗

内容如下:

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

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

下面是我使用的代码:当我提取值并尝试遍历每个\u文件时,它不起作用-print each只打印文件路径的第一个字符[例如:当文件路径为“'C:\Users\xxxxxx\Documents”时为“C”\某物.txt" ]. 请帮我渡过难关。蒂亚。你知道吗

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.

Tags: 文件to字符串in路径forisas
2条回答

我知道了。你知道吗

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()中的每个\u键(每个\u文件,每个\u子字符串):“如果我们不知道需要多少项(这就是它的样子),则效率不是很高”

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

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

相关问题 更多 >