python怎么输入一个列表
时间: 2024-10-21 13:09:28 浏览: 43
在Python中,你可以使用内置函数`input()`或者直接通过键盘输入来获取用户输入的数据,然后将这些数据转换成列表。这里有几个例子:
1. **使用split()函数**:
```python
user_input = input("请输入一个以逗号分隔的元素列表,例如:1,2,3,4 ")
list_items = user_input.split(",")
# 别忘了去掉每个元素末尾的空格
list_items = [item.strip() for item in list_items]
print(list_items)
```
2. **手动逐个添加元素**:
```python
list_items = []
while True:
element = input("请输入一个元素,输入'q'结束:")
if element.lower() == 'q':
break
list_items.append(element)
print(list_items)
```
3. **使用eval()函数**(注意,这不是安全的做法,因为`eval()`会执行任何字符串作为Python代码,仅适用于已知安全的情况):
```python
user_input = input("请输入一个列表,如:['a', 'b', 'c']")
list_items = eval(user_input) # 这种方式只推荐用于测试,生产环境中应避免使用
print(list_items)
```
如果你需要让用户输入的是数字列表,可以指定只能接受整数或浮点数:
```python
list_items = list(map(int, input("请输入以空格分隔的数字列表: ").split()))
```
阅读全文
相关推荐
















