简体   繁体   English

如何将列表中的元素类型存储在 Python 的字典中?

[英]How can I store the types of elements from a list in a dictionary in Python?

How can I store the types of elements from a list in a dictionary?如何将列表中的元素类型存储在字典中? for example to make the output like this:例如使 output 像这样:

datatype_statistic([1,'2',3.5, 0.5, None, (1,1)]) = {
        'int': 1,
        'str': 1,
        'float': 2,
        'None':1,
        'tuple': 1
    }

This is what I did till now but I just do not know what is the method that I should apply to acheive the above:这是我到目前为止所做的,但我只是不知道我应该采用什么方法来实现上述目标:

def datatype_statistic(ls):
     my_list=len(ls)
     print("There are "+str(my_list)+" elements in this list" )
     for item in ls:
        print(type(item))
datatype_statistic([1,'2',3.5, 0.5, None, (1,1)]) 

You can use collections.defaultdict :您可以使用collections.defaultdict

from collections import defaultdict

def datatypes(lst):
    ret = defaultdict(int)
    for x in lst:
        ret[type(x).__name__] += 1
    return dict(ret)

print(datatypes([1, '2', 3.5, 0.5, None, (1, 1)]))

Or, without imports:或者,没有进口:

def datatypes(lst):
    ret = {}
    for x in lst:
        ret[type(x).__name__] = ret.get(type(x).__name__, 0) + 1
    return ret

print(datatypes([1, '2', 3.5, 0.5, None, (1, 1)]))

Output: {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1} Output: {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}

collections.Counter is specifically made for this kind of task: collections.Counter专为此类任务而设计:

from collections import Counter

ls = [1,'2',3.5, 0.5, None, (1,1)]

def datatype_statistic(ls):
    type_names = [type(elem).__name__ for elem in ls]
    return dict(Counter(type_names))

print(datatype_statistic(ls))

Output: Output:

{'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}

I first use a list comprehension to get the type names from the list elements.我首先使用列表推导从列表元素中获取类型名称。 Then I just apply the Counter .然后我只应用Counter Finally I cast to dict to get the output in the requested form.最后,我转换为 dict 以获取所需形式的 output。

Side notes旁注

Note that the calls to .__name__ and dict() are only there to shoe-horn the result to fit the example given for a desired result.请注意,对.__name__dict()的调用只是为了将结果强加于为所需结果给出的示例。 You need to know yourself if you actually need them.如果您真的需要它们,您需要了解自己。

The type of None is NoneType , so that's what I print. None的类型是NoneType ,所以这就是我打印的内容。 You can special-case this if needed.如果需要,您可以对此进行特殊处理。

jake_list = [1, '2', 3.5, 0.5, None, (1, 1)]
datatype_statistic = dict()

for i in jake_list:
    tmp_type = type(i).__name__
    datatype_statistic[tmp_type] = datatype_statistic.get(tmp_type, 0) + 1

# {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}

You would have to employ some form of counter to solve this, which you have not used in your code.您必须使用某种形式的计数器来解决这个问题,而您的代码中没有使用过。

def type_counter_list(list_1):
    count_type = dict()
    for _ in list_1:
        x = type(_)
    if _ in count_type.keys():
        count_type[x]+=1
    else:
        count_type[x]=1
    return count_type

This is not a code, but I guess you are a beginner.这不是代码,但我猜你是初学者。 This is a blueprint for you to develop your code on.这是您开发代码的蓝图。

You can achieve this by using some built-in methods in Python such as map , list.count , and type您可以通过使用 Python 中的一些内置方法来实现此目的,例如maplist.counttype

This is the solution for me:这是我的解决方案:

your_list = [1,'2',3.5, 0.5, None, (1,1)]
x = list(map(lambda j: type(j), your_list))
types_dict = {i.__name__:x.count(i) for i in x} # A dict comprehension
# types_dict value sould be: {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}

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

相关问题 如何在字典python中访问列表中的元素? - How can I access elements inside a list within a dictionary python? 如何在Python中创建包含各种类型元素的列表? - How can I make a list that contains various types of elements in Python? Python:如何从字典中删除元素并将其作为列表返回? - Python: How do I remove elements from a dictionary and return it as a list? 如何通过嵌套在列表中的键从字典中获取元素? - How can I get elements from dictionary by key nested in a list? 如何从列表中分离 Python 字典以进行比较? - How can I isolate a Python dictionary from a list for comparison? 如何根据列表中的元素从Python字典中删除元素? - How to remove elements from a Python dictionary based on elements in a list? 如何将列表存储为字典-Python - How to store a list as a dictionary - python 如何将字典中的键与列表中的元素匹配并将这些键值存储到python中的另一个字典中? - How to match keys in a dictionary with the elements in a list and store those key values to another dictionary in python? 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素? - How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one? 如何在Python中的字典中打印列表? - How can I print list in dictionary in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM