简体   繁体   English

根据条件python3将变量追加到列表

[英]Appending variable to list based on if condition python3

I have a array 我有一个数组

arr=['a','b','c']

and a variable 和一个变量

var='a'

I am trying to remove the variable from array and append the resultant array to a new array. 我试图从数组中删除变量,并将结果数组追加到新数组。

newarray = []

if var in arr:
    newarray.append(arr.remove(var))
    print(newarray)

This does not print anything. 这不会打印任何内容。 However when I run only arr.remove(var) it works...I am not able to append the resultant smaller array to a new variable. 但是,当我只运行arr.remove(var)它可以工作...我无法将结果较小的数组附加到新变量中。

Looks like your code got a bit mangled. 看起来您的代码有点混乱。 Here's how to fix it: 解决方法如下:

arr = ['a','b','c']
var = 'a'
newarray = []

if var in arr:
    newarray.append(var)
    arr.remove(var)
    print(newarray)

To understand why your original code printed [None] , you first need to understand array.remove() . 要了解为什么原始代码[None]打印[None] ,首先需要了解array.remove() array.remove is a void function : it does not return a value, only performs tasks. array.remove是一个void函数 :它不返回值,仅执行任务。 If you try to get or call its return value in a function such as array.append() , Python doesn't know how to react and returns None . 如果您尝试在诸如array.append()类的函数中获取或调用其返回值,Python将不知道如何反应并返回None The None value was then appended to the array properly by the array.append() function. 然后,由array.append()函数将None值正确附加到数组中。

From your description, this is what you may be looking for: 根据您的描述,这可能是您想要的:

arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
    arr.remove(var)
    newarray.append(arr)
    print(newarray)

Output: 输出:

[['b', 'c']]

Note the output of following: 注意以下输出:

if var in arr:
    print(arr.remove(var))
    print(newarray.append(arr))
    print(newarray)

Output: 输出:

None
None
[['b', 'c']]

arr.remove(var) and newarray.append(arr) work on list in place but do not return anything. arr.remove(var)newarray.append(arr)在列表中就位,但不返回任何内容。

Hence newarray.append(arr.remove(var)) means newarray.append(None) 因此newarray.append(arr.remove(var))意味着newarray.append(None)

use pop() function instead. 使用pop()函数代替。 Change: 更改:

newarray.append(var)
print(arr.remove(var))

to: 至:

newarray.append(arr.pop(0))
print(newarr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM