簡體   English   中英

使用if和else在python中列出理解

[英]list comprehension in python with if and else

我測試之后

len_stat = [len(x) if len(x) > len_stat[i] else len_stat[i] for i, x in enumerate(a_list)]

與...相同

for i, x in enumerate(a_list):
    if len(x) > len_stat[i]:
        len_stat[i] = len(x)

當然,但是

len_stat = [len(x) if len(x) > len_stat[a_list.index(x)] else len_stat[a_list.index(x)] for x in a_list]

與...不同

for x in a_list:
    if len(x) > len_stat[a_list.index(x)]:
        len_stat[a_list.index(x)] = len(x)

后來,我知道<list>.index是這里使用的一種不好的方法。

但是為什么它們在后兩個示例中有所不同?


我的錯! 這是我的測試代碼,

a_list = ['Bacteroides fragilis YCH46', 'YCH46', '20571', '-', 'PRJNA13067', 'FCB group', 'Bacteroidetes/Chlorobi group', 'GCA_000009925.1 ', '5.31099', '43.2378', 'chromosome:NC_006347.1/AP006841.1; plasmid pBFY46:NC_006297.1/AP006842.1', '-', '2', '4717', '4625', '2004/09/17', '2016/08/03', 'Complete Genome', 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCF_000009925.1_ASM992v1', 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA_000009925.1_ASM992v1']

len_stat_1 = [0 for x in a_list]
len_stat_2 = [0 for x in a_list]
len_stat_3 = [0 for x in a_list]
len_stat_4 = [0 for x in a_list]

len_stat_1 = [len(x) if len(x) > len_stat_1[i] else len_stat_1[i] for i, x in enumerate(a_list)]

for i, x in enumerate(a_list):
    if len(x) > len_stat_2[i]:
        len_stat_2[i] = len(x)

len_stat_3 = [len(x) if len(x) > len_stat_3[a_list.index(x)] else len_stat_3[a_list.index(x)] for x in a_list]

for x in a_list:
    if len(x) > len_stat_4[a_list.index(x)]:
        len_stat_4[a_list.index(x)] = len(x)

print len_stat_1
print len_stat_2
print len_stat_3
print len_stat_4

輸出:

[26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 1, 1, 4, 4, 10, 10, 15, 63, 63]
[26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 1, 1, 4, 4, 10, 10, 15, 63, 63]
[26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 1, 1, 4, 4, 10, 10, 15, 63, 63]
[26, 5, 5, 1, 10, 9, 28, 16, 7, 7, 72, 0, 1, 4, 4, 10, 10, 15, 63, 63]

如您所見,最后兩個是不同的!

這真的讓我感到困惑。

此列表理解:

len_stat = [len(x) if len(x) > len_stat[a_list.index(x)] else len_stat[a_list.index(x)] for x in a_list]

等效於:

temp = []
for x in a_list:
    temp.append(len(x) if len(x) > len_stat[a_list.index(x)] else len_stat[a_list.index(x)])
len_stat = temp

等效於:

temp = []
for x in a_list:
    if len(x) > len_stat[a_list.index(x)]:
        val = len(x)
    else:
        val = len_stat[a_list.index(x)]
    temp.append(val)
len_stat = temp

當然,除了temp列表以外,它是等效的。 該理解的方法將取代len_stat用一個新的列表,這將始終是相同的長度len_stat將具有任一len(x)為在每x len_stat或將具有len_stat[a_list.index(x)] 您編寫的for循環將根據條件使len_stat發生變化,並且在不知道列表內容的情況下很難確切地說出會發生什么,但是可能會在整個地方更改len_stat值。

要清楚

推薦這種方法,但是我試圖說明理解力與for循環有何不同。

暫無
暫無

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

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