python转化为列表
时间: 2023-09-10 09:08:08 浏览: 39
将一个字符串转化为列表可以使用 Python 中的 `split()` 函数,示例代码如下:
```python
string = "apple banana orange"
list_of_string = string.split()
print(list_of_string)
```
输出结果为:
```
['apple', 'banana', 'orange']
```
其中 `split()` 函数默认以空格为分隔符将字符串分割成多个子字符串,并返回一个列表。如果想要以其他字符为分隔符,可以在 `split()` 函数中指定分隔符的参数,例如:
```python
string = "apple,banana,orange"
list_of_string = string.split(",")
print(list_of_string)
```
输出结果为:
```
['apple', 'banana', 'orange']
```
相关问题
python字典转化为列表
以下是两种将Python字典转化为列表的方法:
1. 使用items()方法将字典转化为键值对列表:
```python
dict_obj = {'a': 1, 'b': 2, 'c': 3}
dict_items = dict_obj.items()
list_obj = [item for item in dict_items]
print(list_obj) # 输出:[('a', 1), ('b', 2), ('c', 3)]
```
2. 使用列表推导式将字典的值转化为列表元素:
```python
dict_obj = {'a': 1, 'b': 2, 'c': 3}
list_obj = [dict_obj[key] for key in dict_obj]
print(list_obj) # 输出:[1, 2, 3]
```
python 集合转化为列表
Python中的集合可以通过使用list()函数将其转换为列表。下面是一个示例:
```python
# 创建一个集合
my_set = {1, 2, 3, 4, 5}
# 将集合转换为列表
my_list = list(my_set)
print(my_list)
```
输出结果为:
```
[1, 2, 3, 4, 5]
```
这样,你就可以将集合转换为列表并进行进一步的操作了。