python如何变为列表,Python中如何将数据转换为列表

原创
admin 19小时前 阅读数 2 #Python

Python中,将值转换为列表的操作非常简单,您只需将值放在方括号内,或者使用list()函数即可,如果您有一个字符串,可以使用以下两种方法将其转换为列表:

1、使用方括号:

s = "Hello, World!"
list_s = [s]
print(list_s)  # 输出:['Hello, World!']

2、使用list()函数:

s = "Hello, World!"
list_s = list(s)
print(list_s)  # 输出:['Hello, World!']

同样,如果您有一个元组,也可以使用这两种方法将其转换为列表。

t = (1, 2, 3)
list_t = [t]
print(list_t)  # 输出:[(1, 2, 3)]

或者:

t = (1, 2, 3)
list_t = list(t)
print(list_t)  # 输出:[(1, 2, 3)]

如果您有一个字典,也可以使用list()函数将其转换为列表。

d = {'a': 1, 'b': 2, 'c': 3}
list_d = list(d)
print(list_d)  # 输出:['a', 'b', 'c']

将字典转换为列表时,只会返回字典的键,如果您需要获取字典的值,可以使用dict.items()dict.values()方法。

d = {'a': 1, 'b': 2, 'c': 3}
items = d.items()  # 返回:[(a, 1), (b, 2), (c, 3)]
values = d.values()  # 返回:[1, 2, 3]
热门