2016-05-31 14 views
-1

我怎麼能更改以下:改變元組的列表中的每個項目的整數值

from itertools import product 
list1 = input().split() 
list2 = input().split() 
result = product(list1, list2) 

for item in result: 
    print(item, end=" ") 

打印:代替

1 2 
3 4 
(1, 3) (1, 4) (2, 3) (2, 4) 

1 2 
3 4 
('1', '3') ('1', '4') ('2', '3') ('2', '4') 

更新:雖然我寫了下面的代碼,它仍然有同樣的問題:

from itertools import product 
list1 = input().split() 
list1_cleaned = [] 
for item in list1: 
    if int(item)>0 and int(item)<30: 
     list1_cleaned.append(int(item)) 
list2 = input().split() 
list2_cleaned = [] 
for item in list2: 
    if int(item)>0 and int(item)<30: 
     list2_cleaned.append(int(item)) 
result = product(list1, list2) 

for item in result: 
    print(item, end=" ") 

和打印:

1 2 
3 4 
('1', '3') ('1', '4') ('2', '3') ('2', '4') 
Process finished with exit code 0 
+0

你爲什麼使用if int(item)> 0和int(item)<30:'? –

+0

@PadraicCunningham https://www.hackerrank.com/challenges/itertools-product –

+1

好的,你只需要按照答案中的建議映射到int,你也可以簡化if if 0

回答

1

這是一種方法。你可以單獨使用地圖,我只想使用lambda。

>>> from itertools import product 
    >>> list1 = input().split() 
    1 2 
    >>> list2 = input().split() 
    3 4 
    >>> to_int = lambda x: map(int, x) 
    #or, result = product(map(int, list1), map(int, list2)) whichever you prefer. 
    >>> result = product(to_int(list1), to_int(list2)) 
    >>> for item in result: 
    ...  print(item, end=" ") 
    ... 
    (1, 3) (1, 4) (2, 3) (2, 4) >>> 

類型:

>>> result = product(to_int(list1), to_int(list2)) 
    >>> for item in result: 
    ... for val in item: 
    ...  print(type(val)) 
    ... 
    <class 'int'> 
    #so on and so forth 

編輯:在您的更新您轉換爲int,並檢查整數是在(0,30),但是當你用product你還有列表字符串。

+0

約束檢查是否可以過濾以及它應該在哪裏? –

+0

這樣的東西'過濾器(lambda x:x> 0和x <30,num)' –

+0

這將工作。雖然如其他評論部分所述,您可以縮短該表達式。 – Pythonista

2

使用list(map(int, input().split()))改變你的輸入字符串轉換爲整數的列表。當你形成你的列表的產品時,你會得到整數的元組而不是數字字符串的元組。