在Python中,读取列表通常意味着从文件、数据库、用户输入或其他数据源中获取数据并存储到列表中。以下是一些常见的方法来读取列表:
1. 从文件读取列表:
使用`open()`函数打开文件,并使用`readlines()`方法读取所有行,然后使用`split()`方法将每行分割成列表中的元素。
with open('file.txt', 'r') as file:
lines = file.readlines()
my_list = [line.strip() for line in lines]
使用`for`循环逐行读取文件内容,并添加到列表中。
with open('file.txt', 'r') as file:
my_list = []
for line in file:
my_list.append(line.strip())
2. 从用户输入读取列表:
使用`input()`函数获取用户输入,并使用`split()`方法将输入分割成列表中的元素。
my_list = input("Enter elements separated by space: ").split()
3. 从其他数据源读取列表:
例如,使用`csv`模块读取CSV文件中的数据。
import csv
with open('file.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
my_list = [row for row in reader]
4. 使用第三方库读取数据:
例如,使用`openpyxl`库读取Excel文件中的一列数据。
import openpyxl
wb = openpyxl.load_workbook('sample.xlsx')
sheet = wb['Sheet1']
column = sheet['B']
my_list = [cell.value for cell in column]
以上是Python中读取列表的一些基本方法。请根据您的具体需求选择合适的方法