包含python

时间:2017-06-02 22:40:13

标签: python regex string list integer

我是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']

1 个答案:

答案 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

此算法使用上一个字典中符合原始条件的值构建一个新字典。