【问题标题】:Create new list from from a single column of existing list?从现有列表的单列创建新列表?
【发布时间】:2018-09-24 08:45:47
【问题描述】:

使用 Python 2.7

现有list:列和相同主机名多个条目:xlist

Index([u'id', u'last_checkin', u'name'], dtype='object')

{'last_checkin': <DateTime '20180411T14:28:18' at 7f0639d26d88>, 'id': 1000017017, 'name': 'linux1v'}
{'last_checkin': <DateTime '20180411T17:18:30' at 7f0639d26dd0>, 'id': 1000019428, 'name': 'linux1v'}
{'last_checkin': <DateTime '20180411T17:18:52' at 7f0639d26e18>, 'id': 1000019430, 'name': 'linux1v'}
{'last_checkin': <DateTime '20180411T17:24:55' at 7f0639d26e60>, 'id': 1000019437, 'name': 'linux1v'}
{'last_checkin': <DateTime '20180411T17:21:18' at 7f0639d26ea8>, 'id': 1000019443, 'name': 'linux1v'}
{'last_checkin': <DateTime '20180411T17:30:26' at 7f0639d26ef0>, 'id': 1000019453, 'name': 'linux1v'}

listzlist

for i in xlist:
  zhostname = i.get('name')
  #print zhostname
  if zhostname not in zlist:
       zlist.append(i)

在第一个list 中,同一主机的多个条目具有不同的last_checkin 日期和/或id。对于新的list,当主机名不存在时,我正在尝试添加到list。但是新的list 似乎是第一个list 的精确副本。就像它不只检查新列表中的主机名。我不关心任何一个条目的 last_checkin 日期或 id

如果我只检查主机名,它如何验证条目?
即:

[if zhostname not in zlist:
   zlist.append(i)]

那么当它在 zlist 中查找主机名时,它是否也在验证其他列并根据整行看到它是不同的?

希望这不像泥巴那么清晰。

我的目标是创建一个没有重复主机名条目的列表,无论id 还是last_checkin

【问题讨论】:

  • 抱歉,这完全不清楚。你的意思是这是一个 pandas dataframe 列,其内容是一个列表? (如果没有,请取消标记pandas)。接下来,不要说“在第一个列表中,同一主机有多个条目具有不同的 last_checkin 日期... id”,请向我们展示您的数据框的一些行,显示 id , last_checkin, name 列。
  • 它可能与您的实际问题没有任何关系,但在您的代码中命名 list 是一个非常糟糕的主意,因为这隐藏了内置 list 数据类型的名称.这也使您的问题相当混乱,因为我不知道您何时说“列表”是指内置列表,还是您的变量名为 list (这似乎不是内置列表,而是数据框或东西)。
  • 是的,我找到了一个使用它的例子......我会改变它。它来自 Redhat 手册。

标签: python python-2.7 list


【解决方案1】:

问题在于 zhostname 只是一个字符串,因此当您使用 zhostname not in zlist 将它与索引对象进行比较时,字符串 zhostname 将永远不会匹配 zlist 中的索引。

我建议使用以主机名作为键的字典。 https://docs.python.org/3/tutorial/datastructures.html#dictionaries

checkins = dict()
for i in xlist:
    zhostname = i.get('name')
    if zhostname not in checkins:
        checkins[zhostname] = i

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2017-10-17
    • 2021-07-10
    • 2021-01-02
    相关资源
    最近更新 更多