Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-如何在列表中存储套接字和用户名?_Python - Fatal编程技术网

Python-如何在列表中存储套接字和用户名?

Python-如何在列表中存储套接字和用户名?,python,Python,有没有办法在列表中存储套接字和用户名?我认为这是不可能的,因为列表中需要一个整数来存储索引。你们推荐我做什么?真的不知道。最简单的方法是在列表中存储元组 l = list() l.add(tuple(username, socket)) print l[0][0], l[0][1] # will print username and soket of first item 或者您可以定义类,例如UserSock,并用该类的实例填充列表 class UserSock: def __in

有没有办法在列表中存储套接字和用户名?我认为这是不可能的,因为列表中需要一个整数来存储索引。你们推荐我做什么?真的不知道。

最简单的方法是在列表中存储元组

l = list()
l.add(tuple(username, socket))

print l[0][0], l[0][1] # will print username and soket of first item
或者您可以定义类,例如UserSock,并用该类的实例填充列表

class UserSock:
    def __init__(self, username, socket):
        self.username = username
        self.socket = socket

l = list()
l.add(UserSock(username, socket))

print l[0].username l[0].socket # will print username and soket of first item

你确定你想把它们放在一个列表而不是一个目录中吗?你能举个例子说明你想完成什么吗?你的问题不太清楚。请注意,
tuple(username,socket)
引发了一个类型错误——你只需使用括号来创建一个tuple,如
(username,socket)
。另外,请注意,您还可以使用,它的优点是(几乎)与元组一样快和轻,但它提供了命名访问器的可读性优势。