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

これは、チャット ボットを対象としています。最初の項目はユーザー名、2 番目の項目は 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読みやすいように最後にaが追加されます。

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 に答える