2017-06-02 72 views
2

我是Python新手。 假設你有python字典,其中值列出了不同的元素。這些值只能包含整數,只能包含字符串或兩者兼有。 我需要找到包含字符串和整數的值。在python中包含整數和字符串的列表

這是我的解決方案,它可以工作,但不是很優雅。

for key,value in dict.iteritems(): 
     int_count=0 
     len_val=len(value) 
     for v in value: 
      if v.isdigit(): 
       int_coun+=1 
     if (int_count!=0 and int_count<len_chr): 
      print value 

我不知道,如果它在概念上可以做這樣的事情正則表達式:

if [0-9].* and [a-z,A-Z].* in value: 
    print value 

或其它有效和優雅的方式。

感謝

編輯

這裏是辭典的例子:

dict={ 'D00733' : ['III', 'I', 'II', 'I', 'I'] 
     'D00734' : ['I', 'IV', '78'] 
     'D00735' : ['3', '7', '18']}    

我要的是:

['I', 'IV', '78'] 
+0

我在這裏遇到問題。你能分享一個樣本字典和你想要得到的輸出嗎? – Mureinik

+0

我添加了一個編輯 – Hrant

+0

我只看到字典中的字符串...沒有整數... –

回答

3

這裏是一個解決方案,你可以嘗試:

import numbers 
import decimal 

dct = {"key1":["5", "names", 1], "Key2":[4, 5, 3, 5]} 

new_dict = {} 

new_dict = {a:b for a, b in dct.items() if any(i.isalpha() for i in b) and any(isinstance(i, numbers.Number) for i in b)} 

這裏是一個解決方案使用正則表達式:

import re 

dct = {"key1":["5", "names", 1], "Key2":[4, 5, "hi", "56"]} 

for a, b in dct.items(): 

    new_list = ''.join(map(str, b)) 

    expression = re.findall(r'[a-zA-Z]', new_list) 

    expression1 = re.findall(r'[0-9]', new_list) 

    if len(expression) > 0 and len(expression1) > 0: 
     new_dict[a] = b 

print new_dict 

該算法建立與以前的字典,滿足原標準值的新字典。

+0

感謝您的解答! 你認爲這也可以用正則表達式來實現嗎?這是我首先想到的。 – Hrant

+0

請參閱我最近的編輯。 – Ajax1234

+0

謝謝,我可以接受你的解決方案,但它仍然不是非常簡單。我的意思是可以很容易地檢查一個特定的元素是否在列表中,比如列表中的「if」9「,所以我想這可能是可能的,而不是特定元素搜索的一系列元素。 – Hrant

相關問題