在列表中收集一个变量

时间:2018-11-03 08:19:20

标签: python python-2.7

$this->ch = curl_init();
    curl_setopt($this->ch, CURLOPT_HEADER, true);
  curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($this->ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($this->ch, CURLOPT_USERAGENT, 'Opera/9.23 (Windows NT 5.1; U; en)');

    // site is returning a gzipped body, force uncompressed
    curl_setopt($this->ch, CURLOPT_ENCODING, 'identity');

我想将列表中的变量作为字符串分配给x,每个新变量都将放在一起,但不能放在最后。 我想要list = [ "test1", "test2", "test3"]

我应该怎么做?

2 个答案:

答案 0 :(得分:2)

尝试一下。只需在列表中添加所有字符串即可。还要避免使用像list这样的关键字的变量名。

output= ""
for item in myList:
    if output == "":
        output += item
    else:
        output  += ', '
        output += item

print(str)

答案 1 :(得分:2)

如果所有列表项均为join,则可以使用str这样获得所需的结果

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

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

此外,请记住,将Python关键字用作变量名不是一个好习惯。

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

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

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

或者,如果您不习惯使用map,则可以像这样在join内使用列表理解

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

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