2017-06-02 71 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

相关问题