Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.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,我想将列表中的变量作为字符串分配给x,每个新变量都会放在一起,但不会放在末尾。 我想要测试,测试2,测试3 我该怎么做?试试这个。只需添加列表中的所有字符串。也要避免使用变量名,这些变量名是像list这样的关键字 如果所有列表项都是str,则可以像这样使用join来获得所需的结果 另外,请记住,使用Python关键字作为变量名不是一个好的做法 如果要对非字符串的其他数据项列表执行相同的操作,可以在列表上使用map,后跟join,如下所示 data = [ "test1", "test2", "t

我想将列表中的变量作为字符串分配给x,每个新变量都会放在一起,但不会放在末尾。 我想要测试,测试2,测试3


我该怎么做?

试试这个。只需添加列表中的所有字符串。也要避免使用变量名,这些变量名是像list这样的关键字

如果所有列表项都是str,则可以像这样使用join来获得所需的结果

另外,请记住,使用Python关键字作为变量名不是一个好的做法

如果要对非字符串的其他数据项列表执行相同的操作,可以在列表上使用map,后跟join,如下所示

data = [ "test1", "test2", "test3"]

print(', '.join(data)) # Output : test1, test2, test3
或者,如果您不习惯使用map,您可以在join中使用列表理解,如下所示

data = [ "test1", "test2", "test3"]

print(', '.join(map(str, data))) # Output : test1, test2, test3

我想你需要澄清一下。你没有变量,你有一个字符串列表。看起来你想加入他们,但我不明白,但没有放在结尾好的ol“”有什么错。joinL?我喜欢你的提示,不要使用关键字作为变量名,如list,这也是我不使用str作为变量的原因name@bereal,那确实短而且好!这就是OP希望在给出答案的基础上实现的目标:感谢您指出错误@Jondiedoop。
data = [ "test1", "test2", "test3"]

print(', '.join(data)) # Output : test1, test2, test3
data = [ "test1", "test2", "test3"]

print(', '.join(map(str, data))) # Output : test1, test2, test3
data = [ "test1", "test2", "test3"]

print(', '.join(str(x) for x in data))