python list tuple简单转换示例

本文展示了如何在Python中将元组转换为列表,以及对列表进行插入和长度变化等操作。同时,尝试对元组进行插入操作时会抛出错误,因为元组是不可变的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

备注:只是简单示例,供有需要时参考使用

代码

本人在python 3.8.9上测试的
list_tuple.py


list1 = ["a", "b", "c", "d"]
tuple1 = (1, 2, 3, 4)


def list_to_tuple(list_args: list) -> tuple:
    print("type is %s" % type(list_args))
    print(list_args)
    return tuple(list_args)


def tuple_to_list(tuple_args: tuple):
    print("type is %s" % type(tuple_args))
    print(tuple_args)
    return list(tuple_args)


def show_list_usage(list_args: list):
    print("type is %s" % type(list_args))
    originalLen = len(list_args)
    list_args.insert(0, "a0")
    list_args.append("z0")

    firstElem = list_args[0]
    lastElem = list_args[-1]
    # 为避免因为%s %d导致类型错误,使用如下这种方式打印
    print('firstElem={}, lastElem={}'.format(firstElem, lastElem))

    print('allElem {}'.format(list_args))
    newLen = len(list_args)
    print("originalLen %d, newLen %d" % (originalLen, newLen))


def show_tuple_usage(tuple_args: tuple):
    print("type is %s" % type(tuple_args))
    print('allElem {}'.format(tuple_args))
    originalLen = len(tuple_args)

    firstElem = tuple_args[0]
    lastElem = tuple_args[-1]
    # 为避免因为%s %d导致类型错误,使用如下这种方式打印
    print('firstElem={}, lastElem={}'.format(firstElem, lastElem))

    # 此处应该报错
    tuple_args.insert(0, "a0")
    print("originalLen %d" % originalLen)


if __name__ == '__main__':
    print("tuple-> list")
    newList = tuple_to_list(tuple1)
    show_list_usage(newList)

    print("\nlist-> tuple")
    newTuple = list_to_tuple(list1)
    show_tuple_usage(newTuple)


效果

/Users/ericyang/PycharmProjects/flashdemo/venv/bin/python /xxx/list_tuple.py
tuple-> list
type is <class 'tuple'>
(1, 2, 3, 4)
type is <class 'list'>
firstElem=a0, lastElem=z0
allElem ['a0', 1, 2, 3, 4, 'z0']
originalLen 4, newLen 6

list-> tuple
type is <class 'list'>
['a', 'b', 'c', 'd']
type is <class 'tuple'>
allElem ('a', 'b', 'c', 'd')
firstElem=a, lastElem=d
Traceback (most recent call last):
  File "xxxxlist_tuple.py", line 57, in <module>
    show_tuple_usage(newTuple)
  File "xxxx/list_tuple.py", line 46, in show_tuple_usage
    tuple_args.insert(0, "a0")
AttributeError: 'tuple' object has no attribute 'insert'

Process finished with exit code 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值