如果我给程序一个列表的特定项目,我想知道如何从列表中检索多个项目。这就是我的列表的样子:
["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
在末尾添加了一个以便于阅读。