Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String_List_Concatenation - Fatal编程技术网

Python 按用户输入(字符串)连接列表并显示列表

Python 按用户输入(字符串)连接列表并显示列表,python,string,list,concatenation,Python,String,List,Concatenation,1) 嗨,我想创建一个程序,用户可以在其中输入字符串和它的附加列表 eg cmd : "hello " cmd : "every " cmd : "one " 'hello' 'every ' 'one' a = 0 while a < 3: b = str(raw_input("cmd : ")) list1 = [b] a += 1 print list1 eg cmd:“你好” cmd:“每个” 指令:“一” “你好”“每个人” a=0 而a

1) 嗨,我想创建一个程序,用户可以在其中输入字符串和它的附加列表

eg cmd : "hello "
   cmd : "every "
   cmd : "one "
'hello' 'every ' 'one'

a = 0
while a < 3:
    b = str(raw_input("cmd : "))
    list1 = [b]
    a += 1

print list1
eg cmd:“你好”
cmd:“每个”
指令:“一”
“你好”“每个人”
a=0
而a<3:
b=str(原始输入(“cmd:”)
列表1=[b]
a+=1
打印列表1
我遇到的问题是在每个循环中将字符串添加到列表中!我错过了发生这种情况的一些逻辑论证。
这些字符串稍后我将分配给某个函数

您需要追加
list1+=[b]
而不是赋值
list1=[b]

在Python中,在本例中最好使用
for in
。另外,原始输入将返回一个字符串,您不需要转换它

for a in range(3):
    b = raw_input("cmd : ")
    list1 += [b]
或者更好地使用列表理解,因为添加列表会产生开销

list1 = [raw_input("cmd : ") for _ in range(3)]

在浏览了论坛的答案后,我想到了一个代码,它可以完全满足我的要求。

我认为使用list1.append(b)(应该更有效,因为不必创建[b]对象。)
list1=[]对于范围内的(2):b=raw\u输入(“cmd:”)list1.append(b)a+=1打印列表1
List1 = []
for a in range(2):
    b = raw_input("cmd :")
    List1.append(b)
    a += 1
print List1