我正在编写一个脚本,我想更改某些句子的顺序
n = 4
l=[]
t = []
for i in range(n):
line = input()
if i%2 == 0:
t += line
else:
l+=line
for i in range(len(l)):
print(l[i])
for i in range(len(t)):
print(t[i])
我按顺序输入以下行:
I like Trains
I like apples
I like pears
I like bananas
我想要打印:
I like apples,
I like bananas,
I like Trains,
I like pears,
但它不打印它,它打印单独的字母。
答案 0 :(得分:2)
您扩展列表,而非追加。 Extending将字符串中的单独元素添加到列表中。
而不是+=
,请使用list.append()
:
t.append(line)
和
l.append(line)
除此之外,您还可以大幅简化打印循环;你可以直接在列表上循环并获取值,不需要用range()
生成索引:
for line in l:
print(line)
for line in t:
print(line)
您可以将整个列表传递给print()
并告诉它打印每个值,并在其间添加换行符:
print(*l, sep='\n')
print(*t, sep='\n')
答案 1 :(得分:0)
n = 4
l = []
t = []
for i in range(n):
line = input(">")
if i % 2 == 0:
t.append(line)
else:
l.append(line)
for i in range(len(l)):
print(l[i])
for i in range(len(t)):
print(t[i])
输出
>I like apple
>I like train
>I like beer
>I like bear
I like train
I like bear
I like apple
I like beer
>>>
n = 4
l = []
t = []
for i in range(n):
line = input(">")
if i % 2 == 0:
t.append(line)
else:
l.append(line)
print(*l, sep="\n")
print(*t, sep="\n")
输出
>1 line
>2 line
>3 line
>4 line
2 line
4 line
1 line
3 line
>>>