转换列表数组

时间:2015-06-03 04:53:57

标签: python list

考虑两个列表的数组:

In [98]: toks
Out[98]:
[['1.423',
  '0.046',
  '98.521',
  '0.010',
  '0.000',
  '0.000',
  '5814251520.0',
  '769945600.0',
  '18775908352.0',
  '2.45024350208e+11',
  '8131.903',
  '168485.073',
  '0.0',
  '0.0',
  '0.022',
  '372.162',
  '1123.041',
  '1448.424'],
 ['71.765',
  '0.478',
  '27.757',
  '0.0',
  '0.0',
  '0.0',
  '5839618048.0',
  '769945600.0',
  '18776162304.0',
  '2.44998729728e+11',
  '0.0',
  '0.0',
  '1640.0',
  '1608.0',
  '0.0',
  '3775.0',
  '12858.0',
  '6723.0']]

所以我们想将列表转换为Point

Point = namedtuple('Point', 'usr sys idl wai hiq siq  used  buff  cach  free 
     read  writ recv  send majpf minpf alloc  vmfree')

直接进行转换可以工作:

  In [99]: Point(*toks[0])
Out[99]: Point(usr='1.423', sys='0.046', idl='98.521', wai='0.010', hiq='0.000', siq='0.000', used='5814251520.0',
 buff='769945600.0', cach='18775908352.0', free='2.45024350208e+11', read='8131.903', writ='168485.073', recv='0.0',
  send='0.0', majpf='0.022', minpf='372.162', alloc='1123.041', vmfree='1448.424')

但是尝试通过迭代创建Point不会:

pts = [map(lambda x: Point(*x), tokarr) for tokarr in toks]


In [90]: pts = [map(lambda x: Point(*x), tokarr) for tokarr in toks0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-90-a30764943aa1> in <module>()
----> 1 pts = [map(lambda x: Point(*x), tokarr) for tokarr in toks0]

<ipython-input-90-a30764943aa1> in <lambda>(x)
----> 1 pts = [map(lambda x: Point(*x), tokarr) for tokarr in toks0]

TypeError: __new__() takes exactly 19 arguments (2 given)

我需要后一种结构,因为目的是迭代一组列表并将每个条目转换为一个Point。怎么做?

2 个答案:

答案 0 :(得分:3)

只需

map

会奏效。

如果您想使用pts = list(map(lambda x: Point(*x), toks))

进行此操作
{{1}}

答案 1 :(得分:2)

我认为您尝试使用map的方式并不合适。您希望lambda应用于根列表的每个元素,而不是每个子列表的每个元素,对吗?

这是你在找什么?

pts = map(lambda x: Point(*x), toks)