从列表列表制作列表

时间:2019-09-19 04:33:11

标签: python python-3.x list

我有以下列表列表

[['Afghanistan,2.66171813,7.460143566,0.490880072,52.33952713,0.427010864,-0.106340349,0.261178523'], ['Albania,4.639548302,9.373718262,0.637698293,69.05165863,0.74961102,-0.035140377,0.457737535']]

我要创建一个仅包含国家/地区名称的新列表。

所以

[Afghanistan, Albania]

当前正在使用此代码。

with open(fileName, "r") as f:
    _= next(f)
    row_lst = f.read().split()
    countryLst = [[i] for i in row_lst]

2 个答案:

答案 0 :(得分:1)

尝试使用split(',')作为list of list中的第一个元素,stringcomma分隔。

>>> lst = [['Afghanistan,2.66171813,7.460143566,0.490880072,52.33952713,0.427010864,-0.106340349,0.261178523'], ['Albania,4.639548302,9.373718262,0.637698293,69.05165863,0.74961102,-0.035140377,0.457737535']]

输出:

>>> [el[0].split(',')[0] for el in lst]                       
['Afghanistan', 'Albania']

说明:

# el[0] gives the first element in you list which a string.
# .split(',') returns a list of elements after spliting by `,`
# [0] finally selecting your first element as required.

编辑1:

使用regex

pattern = r'([a-zA-Z]+)'
new_lst = []
for el in lst:
    new_lst+=re.findall(pattern, el[0])

>>> new_lst     # output          
['Afghanistan', 'Albania']

答案 1 :(得分:0)

看起来像CSV文件。使用csv模块

例如:

import csv

with open(fileName, "r") as f:
   reader = csv.reader(f)
   next(reader) #Skip header
   country = [row[0] for row in reader]