如何将此打印为新列表?

2024-04-25 07:44:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望程序将a列表中的数字打印为一个新的列表x列表,而不是在自己的列表中打印每个数字。你知道吗

当我运行这个时,输出是:

[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 3]

当我只想:

[1, 1, 2, 3]

这是最容易做的事,我不记得怎么做了!有人能帮我吗?谢谢。你知道吗

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []
def less_than_five():
    for item in a:
        if item < 5:
            x.append(item)
        print(x)

less_than_five()

Tags: in程序列表forifdef数字item
3条回答

您可以找到不符合条件的第一个条目的索引,然后从那里切片。这样做的好处是,如果条件在早期得到满足,就不会遍历整个列表。你知道吗

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

index = 0
while index < len(a) and a[index] < 5:
    index += 1

print(a[:index])
# prints: [1, 1, 2, 3]

您可以这样过滤结果:

print(list(filter(lambda x:x<5,a)))

输出:

[1, 1, 2, 3]

或者您也可以尝试列表理解:

print([i for i in a if i<5])

输出:

[1, 1, 2, 3]

您需要将print语句移出for循环:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []
def less_than_five():
    for item in a:
        if item < 5:
            x.append(item)
    print(x)

less_than_five()

结果:

[1, 1, 2, 3]

同样的结果可以通过list comprehension实现:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

x = []

def less_than_five():
    # if original x has to be changed extend is used
    x.extend([item for item in a if item < 5])
    print(x)

less_than_five()

相关问题 更多 >