【问题标题】:Problems with appending a list in Python在 Python 中附加列表的问题
【发布时间】:2017-09-19 12:04:48
【问题描述】:

我每三秒收到一些POST data(准确地说是 384 行)。这些存储在名为data 的列表中。然后我想将它们存储在列表helper 中,每个 POST 之后都会附加data。现在我想查看图中的数据,所以我需要将helper转换为numpy数组,称为myArr

data = json.loads(json_data)["data"] #I get some data
helper=[] #Then create list
helper.append(data) # And here I would like to add values to the end
myArr=np.asarray(helper)

self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("") 


print (len(data))
print(type (data))
print (len(helper))
print(type (helper))
print (len(myArr))
print(type (myArr))
print data

但是当我执行代码时,长度不一样:

>>384
>><type 'list'>
>>1
>><type 'list'>
>>1
>><type 'numpy.ndarray'> 

列表data 内容如下所示:

[[0.46124267578125, 0.0545654296875, 0.89111328125, 0.0, 0.0, 0.0, 0.0],
[0.46124267578125, 0.0545654296898, 0.89111328125, 0.0, 0.0, 0.0, 0.0],
[0.46124267578125, 0.0545654296875, 0.89111328125, 0.0, 0.0, 0.0, 0.0],
[0.4637451171875, 0.05804443359362, 0.8892822265625, 0.0, 0.0, 0.0, 0.0],
[0.4637451171875, 0.05804443359301, 0.8892822265625, 0.0, 0.0, 0.0, 0.0],
[0.4637451171875, 0.05804443359375, 0.8892822265625, 0.0, 0.0, 0.0, 0.0],
[etc.]]

我认为列表的尺寸有问题,我无法弄清楚。

【问题讨论】:

  • 如果你想连接列表,你可以简单地做list_c = list_a + list_b 或者在你的情况下helper += data

标签: python list numpy append


【解决方案1】:

您有一个列表,您可以将另一个列表附加到一个列表中,从而为您提供一个包含一个项目的嵌套列表。简单演示:

>>> data = [1,2,3]
>>> helper = []
>>> helper.append(data)
>>> helper
[[1, 2, 3]]
>>> len(helper)
1

我无法从您的问题中弄清楚为什么您根本需要helper 列表,而是制作一个(浅)复制问题helper = data[:]helper.extend(data)。因为我不确定你从这里要去哪里,所以我会留下这个答案,告诉你为什么你的 helper 列表现在只有一个元素。

【讨论】:

  • 谢谢你的回答,我现在明白了,我在 0. 列表的索引中创建了某种金字塔:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2017-10-15
  • 2021-07-12
相关资源
最近更新 更多