简体   繁体   English

python中包含整数和字符串的列表

[英]list containing integers and strings in python

I am new to Python. 我是Python的新手。 Suppose you have python dictionary, where values are lists different elements. 假设您有python字典,其中的值列出了不同的元素。 These values can contain only integers, only strings or both. 这些值只能包含整数,只能包含字符串或两者都包含。 I need to find values that contain both strings and integers. 我需要找到同时包含字符串和整数的值。

This is my solution, which works but is not very elegant. 这是我的解决方案,虽然有效,但不是很好。

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

I wonder if it is conceptually possible to do something like this regex: 我想知道是否可以在概念上做这样的正则表达式:

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

or in other effective and elegant way. 或以其他有效而优雅的方式。

Thanks 谢谢

EDIT 编辑

Here is an example of dictionary: 这是字典的示例:

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

What I want is: 我想要的是:

['I', 'IV', '78']

Here is a solution that you can try: 您可以尝试以下解决方案:

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)}

Here is a solution using regex: 这是使用正则表达式的解决方案:

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

This algorithm builds a new dictionary with the values from the previous dictionary that meet the original criteria. 该算法使用先前字典中符合原始条件的值来构建新字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM