python - 删除列表中的重复项,但不应根据计数删除第一个首选项

标签 python python-3.x

我有两个列表“myarray”和“u”。列表“myarray”包含名称,它们的计数在列表“u”中。我想删除 myarray 中的重复项及其在 u 中的计数。但我想要保持他们的第一偏好。

myarray=['1.2','2.3','1.00','1.2','1.2','4.7','4.7','3.2','5.5','1.2','4.7'];
u=['hi','hello','bye','hi','hi','nice','ok','yup','i', 'heya', 'ok'];

我已经用过这个方法了,但是怎么会失败呢?

m=list(set(myarray))
print('myarray',m)
counts=list(set(u))
print("counts",counts)

期望的输出:

 myarray=[1.2,2.3,'1.00','4.7',4.7',3.2,'5.5','1.2']
 u=['hi','hello','bye','nice', 'ok','yup','i','heya']

最佳答案

你可以尝试这样的事情:

myarray=['1.2','2.3','1.00','1.2','1.2','4.7','4.7','3.2','5.5','1.2','4.7']
u=['hi','hello','bye','hi','hi','nice','ok','yup','i', 'heya', 'ok']

new_array = []
new_u = []
for word, count in zip(u, myarray):
    if word in new_u:
        continue
    else:
        new_array.append(count)
        new_u.append(word)

print(new_array)
print(new_u)
#  ['1.2', '2.3', '1.00', '4.7', '4.7', '3.2', '5.5', '1.2']
#  ['hi', 'hello', 'bye', 'nice', 'ok', 'yup', 'i', 'heya']

关于python - 删除列表中的重复项,但不应根据计数删除第一个首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43557495/

相关文章:

python - 仅从数据框中获取前三个值

python - 使用 Pandas Python 计算白天站点中断持续时间

Python:从字典创建子字典

python - 使用 SQLAlchemy 连接到数据库

python - 什么时候 `string.swapcase().swapcase()` 不等于 `string` ?

django - 如何从覆盖范围中排除文件?

python - 我对字符串和整数有点困惑,而且我一直收到此错误 : TypeError: list indices must be integers or slices, not str

python - 如何将 Python 单元测试指定为具有数据库依赖性?

python - 如何在 Python 中一个一个打开多个文件并打印内容

python - 获取前一个较小值的索引