问题和列表和单独的字符

问题描述 投票:2回答:2

我正在做一个脚本,我想改变一些句子的顺序

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,

但它不打印它,它打印单独的字母。

python python-3.x list for-loop
2个回答
2
投票

您正在扩展列表,而不是追加。扩展将字符串中的单独元素添加到列表中。

而不是+=,使用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')

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
>>> 

Or... like Martijn said

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
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.