python工作列表的各种方式

时间:2018-12-02 13:14:46

标签: python-3.x

仅尝试查看如何在换行符“ \ n”上分割字符串对象data,并将结果存储在名为rows的变量中。 -然后,使用print()函数显示前五个

f = open('crime_rates.csv', 'r')
data = f.read()

Print(data)  # few lines of data object

Albuquerque,749
Anaheim,371
Anchorage,828
Arlington,503
Atlanta,1379
Aurora,425
Austin,408
Bakersfield,542
Baltimore,1405
Boston,835

第一种方式:

rows = data.split('\n')
print(rows[0:5])

结果1:

['Albuquerque,749', 'Anaheim,371', 'Anchorage,828', 'Arlington,503', 'Atlanta,1379']

第二种方式,这显然不好。.

f = open('crime_rates.csv', 'r')
data = f.read()
for rows in data:
    rows = data.split("\n")
    print(rows[0:5])
    break

结果2:

['Albuquerque,749', 'Anaheim,371', 'Anchorage,828', 'Arlington,503', 'Atlanta,1379']

如何使用列表推导或lambda函数执行此操作:

print([[row[i] for row in data.split("\n")] for i in row[0:5]])

0 个答案:

没有答案