我想根据列表中的值打印字符串。值可以是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
答案 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
由于问题标记为python-2.7,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'