【问题标题】:Figure out if element is present in multi-dimensional array in python找出元素是否存在于python的多维数组中
【发布时间】:2011-02-14 15:21:50
【问题描述】:

我正在解析包含昵称和主机名的日志。我想得到一个包含主机名和最新使用的昵称的数组。

我有以下代码,它只在主机名上创建一个列表:

hostnames = []

# while(parsing):
#    nick = nick_on_current_line
#    host = host_on_current_line 

if host in hostnames:
    # Hostname is already present.
    pass
else:
    # Hostname is not present
    hostnames.append(host)

print hostnames
# ['foo@google.com', 'bar@hotmail.com', 'hi@to.you']

我认为以如下方式结束会很好:

# [['foo@google.com', 'John'], ['bar@hotmail.com', 'Mary'], ['hi@to.you', 'Joe']]

我的问题是找出主机名是否存在于这样的列表中

hostnames = []

# while(parsing):
#    nick = nick_on_current_line
#    host = host_on_current_line   

if host in hostnames[0]: # This doesn't work.
    # Hostname is already present.
    # Somehow check if the nick stored together 
    # with the hostname is the latest one
else:
    # Hostname is not present
    hostnames.append([host, nick])

是否有任何简单的解决方法,或者我应该尝试不同的方法?我总是可以有一个包含对象或结构的数组(如果 python 中有这样的东西),但我更喜欢我的数组问题的解决方案。

【问题讨论】:

    标签: python arrays multidimensional-array


    【解决方案1】:

    使用dictionary 而不是列表。使用主机名作为键,用户名作为值。

    【讨论】:

    • 一个字典可以满足你的所有需求。同一主机的重复更新只会保留最后一个值,访问 dict.items() 将返回 host->nick 条目的数组。
    【解决方案2】:

    只需使用字典即可​​。

    names = {}
    
    while(parsing):
        nick = nick_on_current_line
        host = host_on_current_line   
    
        names[host] = nick
    

    【讨论】:

    • 哇。比我预期的要容易得多。谢谢。
    【解决方案3】:
    if host in zip(*hostnames)[0]:
    

    if host in (x[0] for x in hostnames):
    

    【讨论】:

    • 在集合或字典中测试成员资格比在列表中测试更具可扩展性,尤其是对于作为主机名字符串的可散列项非常好。
    猜你喜欢
    • 2015-12-26
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    相关资源
    最近更新 更多