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