判断元素是否在Python的多维数组中

4 投票
3 回答
2497 浏览
提问于 2025-04-15 22:14

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

我有以下代码,但它只创建了一个主机名的列表:

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中有这样的东西),但我更希望能解决我的数组问题。

3 个回答

2
if host in zip(*hostnames)[0]:

或者

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

用一个字典来代替列表。把主机名当作键,把用户名当作值。

3

直接用字典就可以了。

names = {}

while(parsing):
    nick = nick_on_current_line
    host = host_on_current_line   

    names[host] = nick

撰写回答