gpt4 book ai didi

Python通过ref访问一个对象/需要打标签

转载 作者:太空宇宙 更新时间:2023-11-04 11:03:48 25 4
gpt4 key购买 nike

我需要从标准输入中获取数据并创建一个对象。

传入数据的长度在 5 到 10 行之间。每行都有一个进程号和一个 IP 地址或哈希值。例如:

pid=123 ip=192.168.0.1 - some data
pid=123 hash=ABCDEF0123 - more data
hash=ABCDEF123 - More data
ip=192.168.0.1 - even more data

我需要将这些数据放入类中,例如:

class MyData():
pid = None
hash = None
ip = None
lines = []

我需要能够通过 IP、HASH 或 PID 查找对象。

困难的部分是来自标准输入的多个数据流混合在一起。 (可能有成百上千个进程同时写入数据。)

我有正则表达式提取我需要的 PID、IP 和 HASH,但我如何通过这些值访问对象?

我的想法是做这样的事情:

myarray = {}

for each line in sys.stdin.readlines():
if pid and ip: #If we can get a PID out of the line
myarray[pid] = MyData().pid = pid #Create a new MyData object, assign the PID, and stick it in myarray accessible by PID.
myarray[pid].ip = ip #Add the IP address to the new object
myarray[pid].lines.append(data) #Append the data

myarray[ip] = myarray[pid] #Take the object by PID and create a key from the IP.
<snip>do something similar for pid and hash, hash and ip, etc...</snip>

这为我提供了一个包含两个键(一个 PID 和一个 IP)的数组,它们都指向同一个对象。但是在循环的下一次迭代中,如果我找到(例如)IP 和 HASH 并执行:

myarray[hash] = myarray[ip]

以下是错误的:

myarray[hash] == myarray[ip]

希望这很清楚。我不愿意承认回到 VB 时代,我记得能够通过引用而不是 byval 处理对象。 Python中有类似的东西吗?或者我只是在接近这个错误?

最佳答案

制作两个单独的字典(不要称它们为数组!),byipbyhash -- 为什么您需要将所有内容合并在一起并冒着冲突的风险?!

顺便说一句,您不可能将以下两行背靠背:

myarray[hash] = myarray[ip]
assert not(myarray[hash] == myarray[ip])

要使 assert 保持不变,您必须在两者之间做一些其他事情(扰乱错误命名的 myarray)。

顺便说一句,Python 中的赋值总是通过引用一个对象——如果你想要一个副本,你必须明确地要求一个。

关于Python通过ref访问一个对象/需要打标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com