[英]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
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.