备注:只是简单示例,供有需要时参考使用
代码
本人在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