Python中如何将列表转化为其他数据结构?

def test(pos,target):
	x, y = pos
	color = img[x, y]
    ....
  • 请问上面这两步有办法简写嘛?
  • 假设 pos 很长,都要拆开写入 img[]内,的情况下,类似*参数的写法有嘛?

Python中如何将列表转化为其他数据结构?
4 回复

如果没有理解错的话,pos 类型为 tuple,img[x, y] 调用的内置函数为 getitem,那就直接 img[pos] 就好了。
如图 ![image.png]( https://i.loli.net/2019/10/15/gTp1e3W8oaDAdvu.png)


在Python里,把列表转成其他数据结构很直接,主要用内置函数或对应的构造函数。下面是一些常见的转换场景和代码:

1. 列表转元组tuple() 函数就行,元组不可变。

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # 输出: (1, 2, 3)

2. 列表转集合set() 函数,会自动去重。

my_list = [1, 2, 2, 3, 3]
my_set = set(my_list)
print(my_set)   # 输出: {1, 2, 3}

3. 列表转字典 这需要列表元素是键值对(比如二元组或列表)。用 dict() 函数。

# 元素是二元组
list_of_tuples = [('a', 1), ('b', 2)]
my_dict = dict(list_of_tuples)
print(my_dict)  # 输出: {'a': 1, 'b': 2}

# 元素是列表(长度必须为2)
list_of_lists = [['x', 10], ['y', 20]]
my_dict = dict(list_of_lists)
print(my_dict)  # 输出: {'x': 10, 'y': 20}

4. 列表转字符串join() 方法,元素必须是字符串。

str_list = ['Hello', 'World']
my_string = ' '.join(str_list)
print(my_string)  # 输出: Hello World

# 如果列表里是数字,需要先转成字符串
num_list = [1, 2, 3]
my_string = ''.join(map(str, num_list))
print(my_string)  # 输出: 123

5. 列表转NumPy数组 需要先安装NumPy库 (pip install numpy)。

import numpy as np
my_list = [1, 2, 3, 4]
np_array = np.array(my_list)
print(np_array)         # 输出: [1 2 3 4]
print(type(np_array))   # 输出: <class 'numpy.ndarray'>

6. 列表转Pandas Series 需要安装Pandas (pip install pandas)。

import pandas as pd
my_list = [10, 20, 30]
pd_series = pd.Series(my_list)
print(pd_series)
# 输出:
# 0    10
# 1    20
# 2    30
# dtype: int64

7. 列表转栈或队列 Python列表本身就可以当栈用(appendpop)。当队列用 collections.deque 更高效。

from collections import deque

my_list = [1, 2, 3]
# 转成双端队列(可作队列)
queue = deque(my_list)
queue.append(4)  # 入队
item = queue.popleft()  # 出队
print(item)  # 输出: 1
print(queue) # 输出: deque([2, 3, 4])

总结:根据你的目标数据结构,选择对应的内置函数或库构造函数就行。

#1 上一张复制的有些问题,见这张 ![image.png]( https://i.loli.net/2019/10/15/RkbDN6miOwptyzH.png)

难怪,我传的是 list,会报错 TypeError: argument must be sequence of length 2
转成 tuple 就可以了,感谢。

回到顶部