【问题标题】:i have this list and my for loop that only show odd numbers of list but i want it show only 5 first odd number and if there is not 5 show all of them我有这个列表和我的 for 循环,它只显示列表的奇数,但我希望它只显示 5 个第一个奇数,如果没有 5 则显示所有这些
【发布时间】:2021-12-31 11:07:14
【问题描述】:

代码:

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87,
            23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
for items in num_list:
    if items % 2 != 0:
        print(items)

【问题讨论】:

  • list(filter(lambda x: x%2!=0, num_list))[:5]

标签: python python-3.x list for-loop while-loop


【解决方案1】:

如果我正确理解了您的问题,您可以通过添加这样的计数器来得到您想要的:

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]

counter = 0

for num in num_list:
    if num % 2 != 0 and counter < 5:
        print(num)
        counter += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2014-08-11
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多