Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据列表值打印字符串?_Python_Python 2.7 - Fatal编程技术网

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

Python 如何根据列表值打印字符串?,python,python-2.7,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 因为问题被标记为,所以生成一个新的元组列表。如果您有大量的索引和字符串列表,请考

我想根据列表中的值打印一个字符串。值可以是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
因为问题被标记为,所以生成一个新的元组列表。如果您有大量的索引和字符串列表,请考虑使用或升级到Python 3。


为该模式提供了一个标准的lib函数,消除了显式条件检查的需要。

这是一种优雅的方法。使用itertools中的压缩功能:

>>> a = [str_a,str_b,str_c]
>>> b=  [0,0,1]
>>> ','.join(i for i,j in zip(a,b) if j)
'str_c'
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
>>>

杰出的我完全忽略了这一点。这是正确的方法,因为itertools.compress就是为了这个。哈哈!我一生中从未使用过压缩剂。谁知道我今天会找到一个机会。请在答案中添加指向itertools.compress的链接,这样答案就完整了:)这里:如何在列表中转换该字符串?例如:
string[0]=a,string[1]=c…with.split()
我无法拆分它不太清楚您的意思。为什么斯普利特不适合你?你不想创建一个过滤字符串的列表吗?在
打印字符串之后,我得到了一个示例字符串:
a
c
,现在我想把它转换成一个列表。然后我有一个列表:
string[0]=“a”
string[1]=“b”
。为此,我做了一些类似于
compressed\u list=list(compress(list\u of_strings,index\u list))
的操作,而不是打印(
compress
也返回py2格式的迭代器,所以用
list
将其包装)。
=================== RESTART: C:/Users/Joe/Desktop/stack.py ===================
a
c
>>>