Python list函数

48 篇文章 45 订阅

目录

描述

语法

使用示例

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

2. 将字符串转换为列表

3. 将元组转换为列表

4. 将字典转换为列表

5. 将集合转换为列表

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

注意事项

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

将列表转换为列表


描述

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']

  • 123
    点赞
  • 635
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值