Python设置了一个列表,但保留了原始lis的索引

2024-03-28 09:00:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图设置一个列表,但我想保持其余列表的索引与以前一样。你知道吗

list_a = ['cat','dog','cat','mouse','dog']

list_b = [ 'c','c','c','d','d']

zipped = zip(list_a,list_b)

我想set在list\u a上,但我还想删除list\u b的相应值,该值在设置之后从list\u a中删除。你知道吗

我想要的例子:

new_zip 
>>> [('cat','c'),('dog','c'),('mouse','d')]

我以为压缩2列表可以给我想要的东西,但我可能无法设置压缩列表,因为元组的第二个参数。你知道吗


Tags: 列表new参数ziplist例子cat元组
3条回答

根据您的Python版本,您可以执行以下操作:

Python 2:

dict(zip(list_a, list_b)).items()

Python 3:

list(dict(zip(list_a, list_b)).items())

两者都返回一个元组列表,相当于您要查找的输出。你知道吗

试着查字典?你知道吗

list_a = ['cat','dog','cat','mouse','dog']
list_b = [ 'c','c','c','d','d']
my_dict = {list_a[i] : list_b[i] for i in range(len(list_a))}
print (my_dict)

输出:

{'cat': 'c', 'dog': 'd', 'mouse': 'd'}

现在可以根据需要提取键和值。这能帮你找到解决办法吗?你知道吗

当您不介意使用外部库时,可以使用^{}。它类似于set,但允许使用key-函数并保留遇到的第一个值:

>>> from iteration_utilities import unique_everseen
>>> from operator import itemgetter
>>> list(unique_everseen(zip(list_a, list_b), key=itemgetter(0)))
[('cat', 'c'), ('dog', 'c'), ('mouse', 'd')]

免责声明:^{} package是我写的。但是你可以在^{} Recipes documentation中找到一个几乎相等的配方

相关问题 更多 >