Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—如何使用append将if条件中的值存储到列表中_Python_List_Append - Fatal编程技术网

Python—如何使用append将if条件中的值存储到列表中

Python—如何使用append将if条件中的值存储到列表中,python,list,append,Python,List,Append,代码如下: test('a') test('b') test('c') def test(value): if (value == 'a'): print(value) if (value == 'b'): print(value) if (value == 'c'): print(value) r = [] r.append(value) print('r=', r) 输出将是: a r= ['

代码如下:

test('a')
test('b')
test('c')

def test(value):
    if (value == 'a'):
        print(value)
    if (value == 'b'):
        print(value)
    if (value == 'c'):
        print(value)
    r = []
    r.append(value)
    print('r=', r)
输出将是:

a
r= ['a']
b
r= ['b']
c
r= ['c']
我需要列表“r”存储a、b和c。大概是这样的:

r=['a', 'b', 'c']
可能吗?提前谢谢

试试这个变化

r = []
def test(value):
    if (value == 'a'):
        print(value)
    if (value == 'b'):
        print(value)
    if (value == 'c'):
        print(value)
    global r
    r.append(value)
    print('r=', r)
每次运行函数时,您都在清除列表r。
解决此问题的方法是在全局级别创建列表,并通过函数将参数附加到列表中

您需要将
r
置于
测试函数之外。
像这样:

r=[]
测试('a')
测试('b')
测试('c')
def测试(值):
如果(值='a'):
打印(值)
elif(值='b'):
打印(值)
elif(值='c'):
打印(值)
r、 附加(值)
打印('r=',r)
代码无法达到预期效果的原因:
每次运行
test
功能时,
r
将被清除。

因此,您需要在外部创建
r
,就像上面的代码一样

或者,您可以将它们设置为

类测试:
定义初始化(自):
self.r=[]
def测试(自身、数值):
如果值=='a':
打印(值)
elif值==“b”:
打印(值)
elif值==“c”:
打印(值)
self.r.append(值)
返回自我
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
t=测试()
打印(t检验('a'))#a
打印(t检验('b'))#a,b
打印(t检验('c'))#a,b,c

这没有那么多if语句,仍然会产生预期的结果

value_list = ['a', 'b', 'c']
r = []

def test(value):
    if value in value_list:
        print(value)
        r.append(value)
    return r


for value in value_list:
    print('r={}'.format(test(value)))
输出 笔记 现在for循环遍历列表中的所有值,因此if语句始终为true。如果需要,可以将for循环替换为:

test('a')
print('r={}'.format(r))
test('d') # Not in "value_list"
print('r={}'.format(r))
test('c')
print('r={}'.format(r))
第二输出:
正如您所看到的,这忽略了
值\u列表中没有的值

,就是这样!!!非常感谢。为什么需要这么多if条件?为什么不列出所有要检查的项目,只需有一个条件,即“列表中的值是否为值”\u values:print(value)
可能是示例代码。真正的代码可能会有所不同。如果OP仍然需要更有效的方法,我在底部添加了我的解决方案。这里到底有什么问题?你想要
r=['a'、'b'、'c']
,这不管用吗?
test('a')
print('r={}'.format(r))
test('d') # Not in "value_list"
print('r={}'.format(r))
test('c')
print('r={}'.format(r))
a
r=['a']
r=['a']
c
r=['a', 'c']