0

如果我给程序一个列表的特定项目,我想知道如何从列表中检索多个项目。这就是我的列表的样子:

["randomname", "188.xx.xx.xx", "uselessinfo", "2013-09-04 12:03:18"]
["saelyth", "189.xx.xx.xx", "uselessinfoalso", "2013-09-04 12:03:23"]
["randomname2", "121.xxx.xxx.x", "uselessinfoforstackoverflow", "2013-09-04 12:03:25"]

这适用于聊天机器人。第一项是用户名,第二项是 IP,我需要的是找到与同一 IP 关联的所有名称,然后打印它们或将其发送到聊天,这是我所得到的。

if message.body.startswith("!Track"):
  vartogetname = vartogetip = None
  filename = "listas\datosdeusuario.txt"
  for line in open(filename, 'r'):
    retrieved = json.loads(line)
    if retrieved[0] == targettotrack:
      vartogetname = retrieved[0]
      vartogetip = retrieved[1]
      break
      #So far it has opened the file, check my target and get the right IP to track, no issues until here.
  if not vartogetip == None: #So if has found an IP with the target...
    print("Tracking "+targettotrack+": Found "+str(vartogetip)+"...")
    for line in open(filename, 'r'):
      retrieved2 = json.loads(line)
      if retrieved2[1] == vartogetip: #If IP is found
        if not retrieved2[0] == targettotrack: #But the name is different...
          print("I found "+retrieved2[0]+" with the same ip") #Did worked, but did several different prints.
#HERE i'm lost, read text and comments after this code.
    sendtochat("I found "+retrieved2[0]+" with the same ip") #Only sent 1 name, not all of them :(
  else:
    sendtochat("IP Not found")

我说#HERE是我需要一个代码来添加列表中的项目并将它们添加到另一个列表(我猜?)然后我可以在sendtochat命令中调用它,但是我必须是真的很累,因为我不记得该怎么做。

我正在使用 Python 3.3.2 IDLE,文件中的列表使用 json 保存,并\n在末尾添加了一个以便于阅读。

4

2 回答 2

1

您需要在列表中收集匹配项,然后将该匹配项列表发送您的聊天机器人:

if vartogetip is not None:
    matches = []
    for line in open(filename, 'r'):
        ip, name = json.loads(line)[:2]
        if ip == vartogetip and name != targettotrack:
            matches.append(name)

    if matches:  # matches have been found, the list is not empty
        sendtochat("I found {} with the same ip".format(', '.join(matches)))

', '.join(matches)调用将找到的名称与逗号连接在一起,为名称提供更好、更易读的格式。

于 2013-09-12T08:39:28.680 回答
0

“这适用于聊天机器人。第一项是用户名,第二项是 IP,我需要找到与同一 IP 关联的所有名称,然后将它们打印或发送到聊天,这是据我所知。”

似乎您想要的是一个将 IP 地址字符串映射到与该 IP 地址关联的用户名列表的字典。也许尝试这样的事情:

user_infos = [
["randomname", "188.xx.xx.xx", 'data'],
["saelyth", "189.xx.xx.xx", 'data'],
["randomname2", "121.xxx.xxx.x", 'data'],
["saelyth2", "189.xx.xx.xx", 'data']
]

# Mapping of IP address to a list of usernames :)
ip_dict = {}
# Scan through all the users, assign their usernames to the IP address
for u in user_infos:
    ip_addr = u[1]
    if ip_addr in ip_dict:
        ip_dict[ip_addr].append(u[0])
    else:
        ip_dict[ip_addr] = [u[0]]


# We want to query an IP address "189.xx.xx.xx"
# Let's find all usernames with this IP address
for username in ip_dict["189.xx.xx.xx"]:
    print(username) # Have your chatbot say these names.

这将打印“saelyth”和“saelyth2”,因为它们具有相同的 IP 地址。

于 2013-09-12T08:46:59.933 回答