2017-02-26 143 views
1

我是新來的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) 

任何幫助,將不勝感激!

+1

使用'list(zip(list_a,list_b))'來組合列表。這是更基本的方式。 –

+2

請仔細檢查您的縮進。正如你所寫的,看起來你已經在連續的行上寫了兩個'return'語句,例如,然後繼續這個函數。如果這實際上是您編寫的代碼,那麼您需要查看教程。 – jonrsharpe

+0

@MadPhysicist'zip'在他的情況下不起作用,因爲zip將停止在'(29,20)',因爲他的list_b只有20個值。但是如果你檢查他的結果,那麼用'(30,1)'繼續,等等。 – abccd

回答

3

嘗試以下操作:

a = range(1,20) 
b = range(1,5) 
c = [(x,y) for x in a for y in b if x%y==0] 
print(c) 

它提供了以下輸出

[(1, 1), (2, 1), (2, 2), (3, 1), (3, 3), (4, 1), (4, 2), (4, 4), (5, 1), (6, 1), (6, 2), (6, 3), (7, 1), (8, 1), (8, 2), (8, 4), (9, 1), (9, 3), (10, 1), (10, 2), (11, 1), (12, 1), (12, 2), (12, 3), (12, 4), (13, 1), (14, 1), (14, 2), (15, 1), (15, 3), (16, 1), (16, 2), (16, 4), (17, 1), (18, 1), (18, 2), (18, 3), (19, 1)] 

您可以輕鬆地適應這個爲你的節目,我覺得!

PS:上面的長度爲c會給你元組數。

+0

這是太棒了,簡單優雅!謝謝! – virgiliocyte

+0

如果有幫助,請接受答案。謝謝。 – Ujjwal

0

我還想補充說,你可以使用itertools.cycle來減少你的代碼以獲取元組的原始列表。

from itertools import cycle 

# a and b don't have to be a list unless you need them as a list elsewhere. 
a = range(10, 51) 
b = range(1, 21) 
# cycle the shorter one 
tuple_lst = list(zip(a, cycle(b))) 

print("New tuple count:", len(tuple_lst)) 
print(tuple_lst)