列表长度+列表在不均匀列表上连接

时间:2014-02-02 18:28:56

标签: python list

我有一个像这样的列表列表:

list = [[11, 12, 13, 14] [15, 16, 17]]

我想测量每个子列表的长度

t=[]
for item in list[0]:
    t.append(len(item))

现在我想创建一个匹配的列表列表,其中包含字符串“Point”和先前测量的列表长度中的数字:

new_list=[]

new_list = "Point" += (x)

for i in t:
    x = i+1
    new_list.append (("Point" += (x) += "="))

我希望最终得到一个看起来像这样的列表列表

new_list = [[Point 1, Point 2, Point 3, Point 4][Point 1, Point 2, point 3 ]]

我如何正确地将它们放在一起?

谢谢,

康拉德

3 个答案:

答案 0 :(得分:1)

以下是使用itertools.countstring formatting和嵌套list comprehension的更好方法。

>>> from itertools import count
>>> lis =  [[11, 12, 13, 14], [15, 16, 17]]
>>> c = count(1)
>>> [['Point {} = {}'.format(next(c), y) for y in x] for x in lis]
[['Point 1 = 11', 'Point 2 = 12', 'Point 3 = 13', 'Point 4 = 14'], ['Point 5 = 15', 'Point 6 = 16', 'Point 7 = 17']]

<强>更新

使用enumerate代替itertools.count获取每个子列表的新计数器:

>>> [['Point {} = {}'.format(i, y) for i, y in enumerate(x, 1)] for x in lis]
[['Point 1 = 11', 'Point 2 = 12', 'Point 3 = 13', 'Point 4 = 14'], ['Point 1 = 15', 'Point 2 = 16', 'Point 3 = 17']]

答案 1 :(得分:0)

  

我想测量每个子列表的长度

不使用循环和追加,首选方法是使用列表理解或地图。

lst = [[11, 12, 13, 14], [15, 16, 17]]
map(len, lst)
  

现在我想创建一个由列表组成的匹配列表   字符串“Point”和先前测量的列表长度中的数字:

实际上,您不需要分别计算每个子列表的长度。相反(因为您的列表结构是一致且已知的),创建嵌套列表推导并使用str.format和计数器(itertools.count)以您希望的格式重新创建列表。

<强>实施

>>> lst = [[11, 12, 13, 14], [15, 16, 17]]
>>> from itertools import count
>>> cnt = count(1)
>>> pprint.pprint([["Point {} = {}".format(next(cnt), e)
            for e in sublist] for sublist in lst])

<强>输出

[['Point 0 = 11', 'Point 1 = 12', 'Point 2 = 13', 'Point 3 = 14'],

['Point 4 = 15','Point 5 = 16','Point 6 = 17']]

答案 2 :(得分:0)

另一种方法是使用计数类:

class Count(object):
    def __init__(self, start=0):
        self.count=start

    def __call__(self):
        self.count+=1
        return self.count

c=Count()        
li = [[11, 12, 13, 14], [15, 16, 17]]
print([['Point %i = %i' % (c(),e) for e in sl] for sl in li])  
# [['Point 1 = 11', 'Point 2 = 12', 'Point 3 = 13', 'Point 4 = 14'], ['Point 5 = 15', 'Point 6 = 16', 'Point 7 = 17']]

随着你的更新:

print [['Point %i' % (i) for i, e in enumerate(sl, 1)] for sl in li] 
# [['Point 1', 'Point 2', 'Point 3', 'Point 4'], ['Point 1', 'Point 2', 'Point 3']]