python中的列表遇到麻烦 [英] having trouble with lists in python

查看:86
本文介绍了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']

请解释为什么它们给出不同的输出结果.

解决方案

在第二个函数中,您会看到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):

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:

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

Output:

['a', 'a']

2

['a', 'b', 'a']

Second program:

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

output:

['a', 'a']

2

['a', 'a']

Please explain why these are giving differnt outputs.

解决方案

In your second function you are seeing 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.

In the first you are directly modifying L so you see the changes in L outside the function.

Also never iterate over a list you are removing element from, if you make 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):

这篇关于python中的列表遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆