我是新来的python,我试图找出如何访问和使用存储在元组对(a,b)列表中的整数,这样我可以将b除以b,如果满足条件,则将元组追加到新列表中,然后对元组进行计数。我只想使用基本函数和for循环来做到这一点。访问/使用元组列表中的元素python 3.x
我借了另一个计算器的问题一些代码,我用来创建的元组大小不同的两个独立的整数列出清单,例如:
list_a = list(range(10, 51))
list_b = list(range(1, 21))
new_tuple_list = []
new_tuple_count = 0
for i, a in enumerate(list_a):
new_tuple_list.append((a, list_b[i % len(list_b)]))
divisors_count += 1
print ("New tuple count: ", new_tuple_count)
print (new_tuple_list)
这给了我: 新的元组数:41
[(10, 1), (11, 2), (12, 3), (13, 4), (14, 5), (15, 6), (16, 7), (17, 8), (18, 9), (19, 10), (20, 11), (21, 12), (22, 13), (23, 14), (24, 15), (25, 16), (26, 17), (27, 18), (28, 19), (29, 20), (30, 1), (31, 2), (32, 3), (33, 4), (34, 5), (35, 6), (36, 7), (37, 8), (38, 9), (39, 10), (40, 11), (41, 12), (42, 13), (43, 14), (44, 15), (45, 16), (46, 17), (47, 18), (48, 19), (49, 20), (50, 1)]
但我想知道如果我从(10,1),11乘以2等中除以10,我会得到一个整数,如果是的话,我想将它添加到一个新列表并计算这些元组对的数量。 我已经试过这样:
tuple_test = [(10,1), (11,2)]
def find_divisors (x):
NUM_tuples = []
tuples_count = 0
for x[0] in pairs:
for x[1] in pairs:
if x[0]/x[1] % 2 == 0:
NUM_tuples.append(pairs)
tuples_count += 1
return (x[0]/x[1] % 2)
return NUM_tuples
return tuples_count
find_divisors(tuple_test)
我也尝试过这样的事情:
def divisors(list_a, list_b):
test_int = 0
new_divisors = []
for a in list_a:
for b in list_b:
if a/b % 2 == 0:
test_int += 1
new_divisors += (a,b)
return new_divisors
return test_int
NUM_tuples = []
tuples_count = 0
for i, c in enumerate(list_a):
NUM_tuples.append((c, list_b[i % len(list_b)]))
tuples_count += 1
return tuples_count
return NUM_tuples
divisors(list_a, list_b)
任何帮助,将不胜感激!
使用'list(zip(list_a,list_b))'来组合列表。这是更基本的方式。 –
请仔细检查您的缩进。正如你所写的,看起来你已经在连续的行上写了两个'return'语句,例如,然后继续这个函数。如果这实际上是您编写的代码,那么您需要查看教程。 – jonrsharpe
@MadPhysicist'zip'在他的情况下不起作用,因为zip将停止在'(29,20)',因为他的list_b只有20个值。但是如果你检查他的结果,那么用'(30,1)'继续,等等。 – abccd