Python:有效的展开/扁平列表和单个浮子的列表
我有一个元组和单个浮子的列表,
v = [(1., 2., 3.), (4., 5.), 6., 7.]
现在我想用良好的旧列表理解来将其弄平,
[item for sublist in v for item in sublist]
但是由于单浮子是不可能的,因此发生了错误。展开此混合列表的最有效方法是什么?我尝试浏览列表并使用isininstance()
,但再次,列表是不可能的。
编辑:到目前为止
- 使用HSTACK的时间比较:6.49 µs±100 ns / loop
- hasattr方法:398 ns±2.11 ns / loop
- Collections方法:804 ns±1.27 ns / loop
I have a list of tuples and single floats
v = [(1., 2., 3.), (4., 5.), 6., 7.]
Now I want to flatten it with the good old list comprehension
[item for sublist in v for item in sublist]
But an error occurs as single floats are not iterable. What is the most efficient way to unroll this mixed list? I tried to go through the list and use isininstance()
but once again, the list is not iterable.
EDIT: time comparisons so far
- numpy approach with hstack: 6.49 µs ± 100 ns per loop
- hasattr approach: 398 ns ± 2.11 ns per loop
- collections approach: 804 ns ± 1.27 ns per loop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
hasattr
该对象是可以触及的(具有__ iTer __
方法):输出:
[1.0,2.0,3.0,4.0,5.0,6.0,6.0,7.0]
替代方法是使用
collect> collections.abc
:在这两种情况下,字符串都是可观的,您可能需要根据数据检查此特定情况。
You can use
hasattr
to check if the object is iterable (has a__iter__
method):output:
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
An alternative would be to use
collections.abc
:Note that in both cases, strings are considered iterable, you might want to check for this specific case depending on your data.
使用
numpy
您可以使用 hstack() /a>:With
numpy
you can use hstack():more-itertools package 软件包具有专门用于此问题的函数
-也可以使用字符串 -
The more-itertools package has a function specifically for this problem -
It works with strings too -