使用if和else条件创建列表

时间:2015-12-07 23:56:02

标签: python list

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 

2 个答案:

答案 0 :(得分:1)

你正在寻找像我这样的东西。

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]]
希望这会有所帮助。

答案 1 :(得分:0)

听起来像是在试图将值排序到范围内:

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