列表理解无法按预期工作

时间:2016-06-23 19:35:07

标签: python list-comprehension

在尝试更频繁地使用列表理解时,我尝试将高尔夫编码为编码。所以这有效:

if fraction[0] % i == 0 and fraction[1] % i == 0:
            fraction = [fraction[x]/i for x in range(2)]

但这不起作用:

fraction = [fraction[x]/i for x in range(2) if fraction[0] % i == 0 and fraction[1] % i == 0]

它会出现list index out of range错误

Fraction是一个两项列表,if语句有一个特定的索引,它们永远不会超出范围...想法?

1 个答案:

答案 0 :(得分:1)

问题在于,在第二种情况下,fraction总是被覆盖。

例如,如果fraction = [2, 4]i = 3,您的列表理解将导致fraction == [],而循环将不执行任何操作。

<强>更新

以下是我测试过的代码:

def a(fraction, i):
    if fraction[0] % i == 0 and fraction[1] % i == 0:
        fraction = [fraction[x] // i for x in range(2)]
    return fraction

def b(fraction, i):
    fraction = [fraction[x] // i for x in range(2) if fraction[0] % i == 0 and fraction[1] % i == 0]
    return fraction

print(a([2, 4], 3)) # Output: [2, 4]
print(b([2, 4], 3)) # Ouptut: []

GOLF UPDATE

我认为如果你可以改变测试值的顺序,你的列表理解就可以了。 E.g:

f = next([n//i for n in f] for i in range(max(f),0,-1) if all(n%i==0 for n in f))

测试:

for fraction in ('2/4', '1/5', '4/2', '1/9'):
    f = [int(x) for x in fraction.split('/')]
    f = next([n//i for n in f] for i in range(max(f),0,-1) if all(n%i==0 for n in f))
    print('/'.join(map(str,f)))

# Output:
# 1/2
# 1/5
# 2/1
# 1/9