确定元素是否存在于python的多维数组中

2024-04-30 19:02:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析包含昵称和主机名的日志。我希望最后得到一个数组,其中包含主机名和最近使用的昵称。在

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

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']

我想最后能有一个大致如下的结果会很好:

^{pr2}$

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

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中有这样的东西的话),但是我更喜欢数组问题的解决方案。在


Tags: thehost列表ifisonline数组
3条回答
if host in zip(*hostnames)[0]:

或者

^{pr2}$

就用字典吧。在

names = {}

while(parsing):
    nick = nick_on_current_line
    host = host_on_current_line   

    names[host] = nick

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

相关问题 更多 >