python使用函数改变list

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python使用函数改变list

健忘绅士辣鸡君   2022-09-29 我要评论

python使用函数改变list

函数内改变外部的一个list如果这么写

def rotate(nums, k):
    length=len(nums)
    if length!=0:
        nums=nums[length-k:length]+nums[0:length-k]
 
l=[1,2,3,4,5,6,7]
rotate(l,3)
print(l)

外部的list并没有改变,而返回的是[1, 2, 3, 4, 5, 6, 7]

要改变list中的内容需要这么写

def rotate(nums, k):
    length=len(nums)
    if length!=0:
        nums[:]=nums[length-k:length]+nums[0:length-k]
 
l=[1,2,3,4,5,6,7]
rotate(l,3)
print(l)

这样就返回的是[5, 6, 7, 1, 2, 3, 4]

python list函数用法

描述

list()函数是Python的内置函数。它可以将任何可迭代数据转换为列表类型,并返回转换后的列表。当参数为空时,list函数可以创建一个空列表。

语法

list(object)

名称说明备注
object待转换为列表的数据类型可省略的参数

使用示例

1. 创建一个空列表(无参调用list函数)

>>> test = list()
>>> test
[]

2. 将字符串转换为列表

>>> test = list('cat')
>>> test
['c', 'a', 't']

3. 将元组转换为列表

>>> a_tuple = ('I love Python.', 'I also love HTML.')
>>> test = list(a_tuple)
>>> test
['I love Python.', 'I also love HTML.']

4. 将字典转换为列表

>>> a_dict = {'China':'Beijing', 'Russia':'Moscow'}
>>> test = list(a_dict)
>>> test
['China', 'Russia']

⚠️注意:将字典转换为列表时,会将字典的值舍去,而仅仅将字典的键转换为列表。如果想将字典的值全部转换为列表,可以考虑使用字典方法dict.values()

5. 将集合转换为列表

>>> a_set = {1, 4, 'sdf'}
>>> test = list(a_set)
>>> test
[1, 'sdf', 4]

6. 将其他可迭代序列转化为列表

下面的代码将range类型和map类型的可迭代序列转换为列表:

>>> test1 = list(range(10))
>>> test2 = list(map(int, [23.2, 33.1]))
>>> test1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test2
[23, 33]

注意事项

1. 参数必须是可迭代序列对象

list函数的参数必须是可迭代对象。当选用不可迭代的对象作为参数时,Python报错。

>>> test = list(12)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

将列表转换为列表

可以使用list函数将列表转换为一个列表,这么做Python不会有任何的异常或者报错。它的作用是将参数列表进行深拷贝:

if __name__ == '__main__':
    source_list = ["a", "b", "c", "d"]
    new_list1 = list(source_list)
    print(id(source_list), id(new_list1))
    # output: 4313597760 4312890304
 
    new_list2 = source_list
    print(new_list1)
    # output: ['a', 'b', 'c', 'd']
    print(new_list2)
    # output: ['a', 'b', 'c', 'd']
 
    source_list[0] = "e"
    print(new_list1)
    # output: ['a', 'b', 'c', 'd']
    print(new_list2)
    # output: ['e', 'b', 'c', 'd']

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们