使用if和else条件创建列表

2024-10-03 23:22:39 发布

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

for tup in totalMean:
    if tup >= 12 and tup <=33:
        print tup(list)
    elif tup >= 49 and tup <=52:
        print tup   
    elif tup >= 58 and tup <=67:
        print tup
    elif tup >= 79 and tup <=98:
        print tup 

Tags: andinforiflistprinteliftup
2条回答

你在找这样的东西

totalMean = [98,91,89,82,79,67,58,52,51,49,33,12]
list12_33 = []
list49_52 = []
list58_67 = []
list79_98 = []

for tup in totalMean:
    if tup >= 12 and tup <=33:
        list12_33.append(tup)
    elif tup >= 49 and tup <=52:
        list49_52.append(tup)
    elif tup >= 58 and tup <=67:
        list58_67.append(tup)
    elif tup >= 79 and tup <=98:
        list79_98.append(tup)

print [list12_33, list49_52, list58_67, list79_98]

结果如下:

[[33, 12], [52, 51, 49], [67, 58], [98, 91, 89, 82, 79]]

希望这有帮助

听起来像是你在尝试将值按范围排序:

totalMean = [33, 12, 52, 51, 49, 67, 58, 98, 91, 89, 82, 79]
buckets = {limits: [] for limits in ((12, 33), (49, 52), (58, 67), (79, 98))}

for tup in totalMean:
    for lo, hi in buckets:
        if lo <= tup <= hi:
            buckets[(lo, hi)].append(tup)
            break

result = [sorted(buckets[limits]) for limits in sorted(buckets)]
print(result)

输出:

[[12, 33], [49, 51, 52], [58, 67], [79, 82, 89, 91, 98]]

相关问题 更多 >