python中的列表遇到麻烦 [英] having trouble with lists in python
问题描述
函数satisfiesF()将字符串列表L作为参数.函数f将字符串作为参数返回true或false.函数satisfiesF()将L修改为仅包含f(s)返回true的那些字符串. 我有两个旨在产生相同输出的不同程序.但是我得到了不同的输出.
第一个程序:
def f(s):
return 'a' in s
def satisfiesF(L):
k=[]
for i in L:
if f(i)==True:
k.append(i)
L=k
print L
print
return len(L)
L = ['a', 'b', 'a']
print satisfiesF(L)
print L
输出:
['a','a']
2
['a','b','a']
第二个程序:
def f(s):
return 'a' in s
def satisfiesF(L):
for i in L:
if f(i)==False:
L.remove(i)
print L
print
return len(L)
L = ['a', 'b', 'a']
print satisfiesF(L)
print L
输出:
['a','a']
2
['a','a']
请解释为什么它们给出不同的输出结果.
在第二个函数中,您会看到 首先,您直接修改 如果执行以下操作,也永远不要遍历要从中删除元素的列表
The function satisfiesF() takes a list L of strings as a paramenter. function f takes a string as a parameter returns true or false. Function satisfiesF() modifies L to contain only those strings,s for which f(s) returns true.
I have two different programs aimed to produce the same output. But I am getting different outputs. First program: Output: ['a', 'a'] 2 ['a', 'b', 'a'] Second program: output: ['a', 'a'] 2 ['a', 'a'] Please explain why these are giving differnt outputs. In your second function you are seeing In the first you are directly modifying Also never iterate over a list you are removing element from, if you make
这篇关于python中的列表遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!2
作为长度以及函数外部L
中的所有元素,因为您正在设置局部变量k
的引用,因此在函数外部创建的L
不会受到影响.要查看L
中的更改,您将需要使用L[:] = k
,然后在更改传递到函数中的原始列表对象L
列表时,打印L
将在功能外提供['a', 'a']
. /p>
L
,以便在功能之外看到L
中的更改.L = ['a', 'b', 'a','a','d','e','a']
,您将获得意想不到的行为.复制for i in L[:]
或使用反向的for i in reversed(L):
def f(s):
return 'a' in s
def satisfiesF(L):
k=[]
for i in L:
if f(i)==True:
k.append(i)
L=k
print L
print
return len(L)
L = ['a', 'b', 'a']
print satisfiesF(L)
print L
def f(s):
return 'a' in s
def satisfiesF(L):
for i in L:
if f(i)==False:
L.remove(i)
print L
print
return len(L)
L = ['a', 'b', 'a']
print satisfiesF(L)
print L
2
as the length and all the elements in L
outside the function because you are setting a local variableL
which is a reference to k
, your L
created outside the function is not affected. To see the change in L
you would need to use L[:] = k
, then printing L
will give you ['a', 'a']
outside the function as you are changing the original list object L
list passed in to the function.L
so you see the changes in L
outside the function.L = ['a', 'b', 'a','a','d','e','a']
, you will get behaviour you won't expect. Either make a copy for i in L[:]
or use reversed for i in reversed(L):