如何根据列表值打印字符串?

时间:2016-09-19 08:05:41

标签: python python-2.7

我想根据列表中的值打印字符串。值可以是0或1.例如:

# Example [a,b,c] = [0,0,1] -- > print str c
# [1,0,1] -- print str a and str c

index_list = [0,0,1] # Example      
str_a = "str_a"
str_b = "str_b"
str_c = "str_c"

print str

3 个答案:

答案 0 :(得分:7)

这是一种优雅的方式。在itertools中使用compress函数:

import itertools as it
l1 = [1, 0, 1]
l2 = ["a", "b", "c"]
for item in it.compress(l2, l1):
    print item

输出:

=================== RESTART: C:/Users/Joe/Desktop/stack.py ===================
a
c
>>>

答案 1 :(得分:4)

for condition, string in zip(index_list, [str_a, str_b, str_c]):
    if condition:
        print string

由于问题标记为zip会生成新的元组列表。如果您有大量索引和字符串,请考虑使用itertools.izip或升级到python 3。

This answer为此模式提供了一个标准的lib函数,无需显式条件检查。

答案 2 :(得分:2)

>>> a = [str_a,str_b,str_c]
>>> b=  [0,0,1]
>>> ','.join(i for i,j in zip(a,b) if j)
'str_c'