數組考慮兩個列表的數組:轉化名單
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 = 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')
但嘗試通過迭代創建點不會:
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。這個怎麼做?
您應該使用地圖或列表理解。 – Alik
@Alik請明確表示:即顯示一些代碼。如果您注意到OP包含嘗試的列表理解。 – javadba
我不明白你想用''map'實現什麼。 ''[tokarr] [tokarr]不是'''足夠嗎? – fjarri