python - 合并 2 个数组以获得 python 中的唯一值

标签 python arrays string list

有 2 个 df 列,我想将它们合并在一起。由于大多数值在相应行之间是相等的,我想创建一个列,其中每一行的值都是唯一的。

实现以下输出的最佳方法是什么?

示例:

list1 = ['','','dog','cat','cat']
list2 = ['dog','','dog','cat','']

输出:

combined_list = ['dog','','dog','cat','cat']

最佳答案

我们可以在这里使用or运算符:

[x or y for x, y in zip(list1, list2)]

鉴于第一项具有真实性 False(这是空字符串的情况),它采用第二个元素。如果第一个元素具有真实性 True,则它采用第一个元素。

对于给定的样本输入,我们得到:

>>> [x or y for x, y in zip(list1, list2)]
['dog', '', 'dog', 'cat', 'cat']

如果两个元素都有非空字符串,则它将采用第一个字符串。

关于python - 合并 2 个数组以获得 python 中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208550/

相关文章:

python - 如何在python中将信息保存到文件中? (简单的编程)

python - 如何计算包含一组列中的值和 Pandas 数据框中另一列中的另一个值的行数?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 从 cakephp 查询中获取平面数组

python - 摆脱python中字符串中的某些字符

Python argparse parse_args 到全局命名空间(或者这是一个坏主意的原因)

python - 使 Python 脚本面向对象

javascript - 为什么 Array.indexOf() 对一个 redux Action 正确工作,但对另一个 Action 却不行? (相同的 reducer )

python - 在 Pandas 中将字符串转换为时间增量

java - 使用 long 计算素数 (Java)