2015-01-02 34 views
0

我正在解決python中的一個問題。比較2個字符串A和B中的數字

我有2串數字和我需要找出從字符串B中的號碼是否位於一個字符串A.

例如:

a = "5, 7" 
b = "6,5" 

A和B可以包含任意數量和數量。

如果字符串B的數量在A中我想要結果是true或false。

不幸的是,我不知道該怎麼做。

+0

是數字的整數? – xnx

回答

5

你有一個字符串,不是整數,所以你必須要他們先轉換爲整數:

a_nums = [int(n) for n in a.split(',')] 
b_nums = [int(n) for n in b.split(',')] 

這將使用list comprehension打開的每個結果一個str.split() methodint() function調用整數。

爲了測試是否有在兩個序列中都是數字,你會使用sets,然後進行測試,如果有一個交叉點:

set(a_nums) & set(b_nums) 

如果結果不爲空,有序列之間共享的數字。由於非空套are considered 'true',在Python中,你會將此轉換爲布爾與bool()

bool(set(a_nums) & set(b_nums)) 

集是迄今爲止最有效的方法來測試這種交叉點。

你可以做到這一切在一個行,多一點有效,用生成器表達式和set.intersection() method

bool(set(int(n) for n in a.split(',')).intersection(int(n) for n in b.split(','))) 

或許與map()功能多一點的緊湊依然:

bool(set(map(int, a.split(','))).intersection(map(int, b.split(',')))) 

演示:

>>> a = "5, 7" 
>>> b = "6,5" 
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(',')))) 
True 

或佈雷亞王下來一點:

>>> [int(n) for n in a.split(',')] 
[5, 7] 
>>> [int(n) for n in b.split(',')] 
[6, 5] 
>>> set(map(int, a.split(','))) 
set([5, 7]) 
>>> set(map(int, a.split(','))).intersection(map(int, b.split(','))) 
set([5]) 
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(',')))) 
True 
+0

是啊,沒關係,THX –

3

如果數字是整數,以獲得對應於b每個號碼是否在aTrue/False條目的列表,請嘗試:

a = "5, 7" 
b = "6,5" 
A = [int(x) for x in a.split(',')] 
B = [int(x) for x in b.split(',')] 
c = [x in A for x in B] 
print(c) 

輸出:

[False, True] 

要找到如果b中的數字在a,那麼:

any(c) 

輸出:

True 
+0

我只想要1個結果=我不比較6與5和5與7,但6與5和7 –

+0

這種解決方案,例如,如果「b =」7 ,5" ' – xnx

1
#This should do the trick 
a_ints = [int(i) for i in a.split(',')] 
b_ints = [int(i) for i in b.split(',')] 
for item in b_ints: 
    for items in a_ints: 
     if item==items: return true 
return false