python修改函数中的列表切片 [英] python Modifying slice of list in function

查看:150
本文介绍了python修改函数中的列表切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

def func1(a):
    a[:] = [x**2 for x in a]

a = range(10)
print a  #prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
func1(a[:5])
print a  #also prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我希望发送列表a的一部分,并在函数内对其进行更改.我的预期输出是

I wish to send a slice of the list a and change it inside the function. My expected output is

[0, 1, 4, 9, 16, 5, 6, 7, 8, 9]

哪种方法是惯用的方法?

Which way is the idiomatic way to do so?

谢谢!

推荐答案

如果对列表进行切片,则只能修改一个副本,因此您要执行的操作无法按照您想要的形式进行.

If you slice the list, you modify only a copy, so what you want to do doesn't work in the form you want.

但是您可以将可选的slice对象传递给func1,如果不是None,则使用它来执行切片分配(否则使用[:])

But you could pass an optional slice object to func1 and if it's not None, use it to perform the slice assignment (else use [:])

我将执行以下操作(使用lambda来避免复制/粘贴公式,并使用生成器表达式来避免创建无用的临时列表:

I would do the following (used a lambda to avoid copy/paste of the formula and a generator expression to avoid creating a useless temporary list:

def func1(a,the_slice=None):
    e = lambda y : (x**2 for x in y)
    if the_slice:
        a[the_slice] = e(a[the_slice])
    else:
        a[:] = e(a)

测试:

a = list(range(10))
func1(a)
print(a)
a = list(range(10))
func1(a,slice(5))   # stop at 5
print(a)
a = list(range(10))
func1(a,slice(5,len(a),2))  # start at 5 / stop at the end, stride/step 2
print(a)

结果:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 25, 6, 49, 8, 81]

  • 在第一种情况下,列表的总数已更改
  • 在第二种情况下,它仅更改了前半部分.
  • 在第三种情况下,它更改了下半部分,但是2中有1个值(步幅= 2)
  • 这篇关于python修改函数中的列表切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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