【问题标题】:How to remove a specific data type from a list如何从列表中删除特定数据类型
【发布时间】:2021-09-24 10:06:25
【问题描述】:

一个列表可以由不同的数据类型组成。那么如何分离数据类型,例如将整数存储在自己的列表中,将字符串存储在自己的列表中,甚至浮点数。像这样的清单 name = [“国王”,'数据',22,33,2.5,3.5] 我需要一些能够让我们说将字符串从名称列表添加到新的空列表的代码

【问题讨论】:

标签: python string list floating-point integer


【解决方案1】:
from collections import defaultdict
input_list = ["king", 'data', 22, 33, 2.5, 3.5] 
d = defaultdict(list)
for v in input_list:
    d[type(v)].append(v)

例如,如果你只需要字符串:

strings = d[str]  # ['king', 'data']

【讨论】:

    【解决方案2】:
    name = ["king",'data',22,33,2.5,3.5]
    str_list = []
    num_lists = []
    
    for elem in name:
        if type(elem) == str:
            str_list.append(elem)
        elif type(elem) == int:
            num_lists.append(elem)
            
            
    print(name)
    print(str_list)
    print(num_lists)
    

    【讨论】:

      【解决方案3】:

      您可以使用 isinstance() 方法检查给定的数据类型:

      lst = ["king", "data", 22, 33, 2.5, 3.5]
      
      f = []
      s = []
      i = []
      o = []
      
      # for each item in the list
      for item in lst:
          # if an item is a string
          if isinstance(item, str):
              # append the item to s list
              s.append(item)
          elif isinstance(item, int):
              i.append(item)
          elif isinstance(item, float):
              f.append(item)
          else:
              o.append(item)
          
      print(f, s, i)
      

      【讨论】:

        【解决方案4】:

        你在找这个吗

        names = ["king",'data',22,33,2.5,3.5]
        l = [n for n in names if isinstance(n, str)]
        

        输出:

        ['king', 'data']
        

        【讨论】:

        • 您可以添加“str”作为变量,并根据需要将 int 或 str 分开
        猜你喜欢
        • 2018-04-13
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        • 2021-11-15
        相关资源
        最近更新 更多