簡體   English   中英

帶有If Else的Python嵌套列表理解

[英]Python Nested List Comprehension with If Else

我試圖使用列表推導來替換值列表中的多個可能的字符串值。

我有一個來自cursor.description的列名列表;

['UNIX_Time', 'col1_MCA', 'col2_MCA', 'col3_MCA', 'col1_MCB', 'col2_MCB', 'col3_MCB']

然后我有header_replace ;

{'MCB': 'SourceA', 'MCA': 'SourceB'}

我想用這些值替換在列名中找到的header_replace.keys()的字符串值。

我不得不使用以下循環;

headers = []
for header in cursor.description:
    replaced = False
    for key in header_replace.keys():
        if key in header[0]:
            headers.append(str.replace(header[0], key, header_replace[key]))
            replaced = True
            break

    if not replaced:
        headers.append(header[0])

這給了我正確的輸出;

['UNIX_Time', 'col1_SourceA', 'col2_SourceA', 'col3_SourceA', 'col1_SourceB', 'col2_SourceB', 'col3_SourceB']

我嘗試使用此列表理解;

[str.replace(i[0],k,header_replace[k]) if k in i[0] else i[0] for k in header_replace.keys() for i in cursor.description]

但這意味着要為不匹配的密鑰復制項目,我會得到;

['UNIX_Time', 'col1_MCA', 'col2_MCA', 'col3_MCA', 'col1_SourceA', 'col2_SourceA', 'col3_SourceA', 
'UNIX_Time', 'col1_SourceB', 'col2_SourceB', 'col3_SourceB', 'col1_MCB', 'col2_MCB', 'col3_MCB']

但是,如果我使用;

[str.replace(i[0],k,header_replace[k]) for k in header_replace.keys() for i in cursor.description if k in i[0]]

@Bakuriu固定語法

我會得到正確的替換,但是然后松開不需要替換字符串的所有項目。

['col1_SourceA', 'col2_SourceA', 'col3_SourceA', 'col1_SourceB', 'col2_SourceB', 'col3_SourceB']

有沒有做到這一點的怪誕方式,還是我過度擴展列表理解力? 我當然覺得它們很難閱讀。

[str.replace(i[0],k,header_replace[k]) if k in i[0] for k in header_replace.keys() for i in cursor.description]

這是一個SyntaxError ,因為if表達式必須包含else部分。 您可能的意思是:

[i[0].replace(k, header_replace[k]) for k in header_replace for i in cursor.description if k in i[0]]

if結尾。 但是我必須說,嵌套循環的列表理解通常不是要走的路。 我將使用擴展的for循環。 實際上,我會改進它以除去replaced標志:

headers = []
for header in cursor.description:
    for key, repl in header_replace.items():
        if key in header[0]:
            headers.append(header[0].replace(key, repl))
            break
    else:
        headers.append(header[0])

如果在迭代過程中未觸發break則執行for循環的else


我不明白為什么在您的代碼中使用str.replace(string, substring, replacement) string.replace(substring, replacement) str.replace(string, substring, replacement)而不是string.replace(substring, replacement) 字符串具有實例方法,因此就這樣使用它們,而不是像它們是類的靜態方法一樣。

如果您的數據完全符合您的描述,則不需要嵌套替換,可以將其簡化為以下一行:

l = ['UNIX_Time', 'col1_MCA', 'col2_MCA', 'col3_MCA', 'col1_MCB', 'col2_MCB', 'col3_MCB']
[i.replace('_MC', '_Source')  for i in l]

>>> ['UNIX_Time',
>>>  'col1_SourceA',
>>>  'col2_SourceA',
>>>  'col3_SourceA',
>>>  'col1_SourceB',
>>>  'col2_SourceB',
>>>  'col3_SourceB']

我猜一個函數將更具可讀性:

def repl(key):
    for k, v in header_replace.items():
        if k in key:
            return key.replace(k, v)
    return key

print map(repl, names)

另一個(不太可讀)的選項:

import re
rx = '|'.join(header_replace)
print [re.sub(rx, lambda m: header_replace[m.group(0)], name) for name in names]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM