python - 在追加到数组的情况下,Python 中的短 "if"

标签 python python-2.7 if-statement

我想使用内联 if 语句将数据附加到数组(如果数组中尚不存在),如下所示:

arr.append( data if not data in arr )

但是这段代码返回:

SyntaxError: invalid syntax

还有其他选择吗?

最佳答案

用途:

arr.extend([data] if data not in arr else [])

示例

让我们从一个示例数组开始:

>>> arr = [1, 2, 3]

现在让我们尝试 data = 4不在 arr 中:

>>> data = 4
>>> arr.extend([data] if data not in arr else [])
>>> arr
[1, 2, 3, 4]

现在让我们尝试 data = 2这是 arr 中已有的值:

>>> data = 2
>>> arr.extend([data] if data not in arr else [])
>>> arr
[1, 2, 3, 4]

剩下arr保持原样不变。

注释

  1. append会追加一些东西。因为看起来我们只想在数据不在 arr 中时追加,这不是正确的使用方法。方法extend避免了这个问题。

  2. [data] if data not in arr else []将返回[data]如果data不在 arr 中。否则,它将返回 [] .

  3. arr.extend([])叶子arr不变。

  4. arr.extend([data])添加元素dataarr结束.

关于python - 在追加到数组的情况下,Python 中的短 "if",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553967/

相关文章:

python - 使用 textblob 或 spacy 更正法语拼写

python - 将数字数据(保存在文本文件中)读取到Python中的正确方法是什么?

if-statement - VB6 IIf优势

c - 用什么代替模数?

if-statement - 在报表中使用数字或字母代码;用于 "if"语句中

Python:set.pop() 的用例是什么?

python - Weasel 程序,不懂 Python 随机库?

python - Python 中的共现矩阵,scipy coo_matrix

python - 将参数传递给 fsolve

python - Matplotlib dpi 被忽略