在Python 3x中对列表/元组执行计算的最佳方法

Best way to perform calculations on a list/tuple in Python 3x

我编写了这个程序,它将告诉您输入的两个系数。如果我输入35(半素数),程序将打印5和7,这两个素数乘以35。

但是我想知道是否有一种更简洁或者更具Python式的方法来迭代这个元组,这样我就不必编写您在下面看到的所有"elif"语句了。

另外,如果我不需要依赖任何外部的库,那就太好了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )

# tuple 1 calculations
while True:

        try:
                semiprime = int(input('Enter Semiprime: '))

        except ValueError:
                print('INPUT MUST BE AN INTEGER')
                continue

        # index 0 - 3
        if (tuple1[0]) * (tuple1[0]) == semiprime:
                print((tuple1[0]), (tuple1[0]))

        elif (tuple1[0]) * (tuple1[1]) == semiprime:
                print((tuple1[0]), (tuple1[1]))

        elif (tuple1[0]) * (tuple1[2]) == semiprime:
                print((tuple1[0]), (tuple1[2]))

        elif (tuple1[0]) * (tuple1[3]) == semiprime:
                print((tuple1[0]), (tuple1[3]))

        # index 1 - 3
        elif (tuple1[1]) * (tuple1[0]) == semiprime:
                print((tuple1[1]), (tuple1[0]))

        elif (tuple1[1]) * (tuple1[1]) == semiprime:
                print((tuple1[1]), (tuple1[1]))

        elif (tuple1[1]) * (tuple1[2]) == semiprime:
                print((tuple1[1]), (tuple1[2]))

        elif (tuple1[1]) * (tuple1[3]) == semiprime:
                print((tuple1[1]), (tuple1[3]))

        # index 2 - 3
        elif (tuple1[2]) * (tuple1[0]) == semiprime:
                print((tuple1[2]), (tuple1[0]))

        elif (tuple1[2]) * (tuple1[1]) == semiprime:
                print((tuple1[2]), (tuple1[1]))

        elif (tuple1[2]) * (tuple1[2]) == semiprime:
                print((tuple1[2]), (tuple1[2]))

        elif (tuple1[2]) * (tuple1[3]) == semiprime:
                print((tuple1[2]), (tuple1[3]))

        #index 3 - 3
        elif (tuple1[3]) * (tuple1[0]) == semiprime:
                print((tuple1[3]), (tuple1[0]))

        elif (tuple1[3]) * (tuple1[1]) == semiprime:
                print((tuple1[3]), (tuple1[1]))

        elif (tuple1[3]) * (tuple1[2]) == semiprime:
                print((tuple1[3]), (tuple1[2]))


我在我的评论中暗示过这一点,但我意识到仅仅链接到功能文档可能不够。

以下是使用itertools.combinations_with_replacement编写代码的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from itertools import combinations_with_replacement

# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )

# tuple 1 calculations
while True:

    try:
        semiprime = int(input('Enter Semiprime: '))

    except ValueError:
        print('INPUT MUST BE AN INTEGER')
        continue

    for (x,y) in combinations_with_replacement(tuple1, 2):
        if x * y == semiprime:
            print(x,y)

好多了,我说:)

编辑:以前的版本使用的itertools.combinations不会产生具有相同值的(x,y)对(例如(x,y) = (2,2))。combinations_with_replacement允许重复。感谢@copperfield指出这一点。


虽然Jedwards展示了最为Python式的方法——使用你会了解和喜爱的itertools库——这里有一种更为"经典"的方法,用于你想要的模式的循环。我之所以提到它,是因为作为一个编程初学者,了解这个基本的命令式习语很重要:

1
2
3
4
5
6
7
8
9
10
11
12
>>> tuple1 = (2,3,5,7)
>>> for i in range(len(tuple1)):
...   for j in range(i+1, len(tuple1)):
...     print(tuple1[i], tuple1[j])
...
2 3
2 5
2 7
3 5
3 7
5 7
>>>

因此,您的代码将被缩短为:

1
2
3
4
for i in range(len(tuple1)):
    for j in range(i+1, len(tuple1)):
        if tuple1[i] * tuple1[j] == semiprime
            print(tuple1[i], tuple1[j])


尽管@jedwards解决方案很棒(以及简洁的/Python式的);另一个可能的解决方案是:

1
2
3
4
5
6
7
8
def prime_multiples(l,t ):  
    for i in l:  # Iterate over our list.
        for j in t:  # Iterate over the tuple of prime factors.
            #  We check to see that we can divide without a remainder with our factor,
            #  then check to see if that factor exists in our tuple.
            if i%j == 0 and i/j in t:
                print"Prime factors: {} * {} = {}".format(j, i/j, i)
                break  # We could go not break to print out more options.

样品输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
l = [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49]
t = ( 2, 3, 5, 7 )
prime_multiples(l, t)
>>> Prime factors: 2 * 2 = 4
... Prime factors: 2 * 3 = 6
... Prime factors: 3 * 3 = 9
... Prime factors: 2 * 5 = 10
... Prime factors: 2 * 7 = 14
... Prime factors: 3 * 5 = 15
... Prime factors: 3 * 7 = 21
... Prime factors: 5 * 5 = 25
... Prime factors: 5 * 7 = 35
... Prime factors: 7 * 7 = 49