交换列表中的数字项 [英] swapping numeric items in a list
问题描述
我简化了下面的问题
转换列表
aa = [0x12 ,0x34,0x56,0x78]
进入
[0x34,0x12,0x78,0x56]
如何快速完成?我真实的名单很大。
非常感谢。
Jason
for x in xrange(0,len(your_list),2):
your_list [i],your_list [i + 1] = your_list [i + 1],your_list [ i]
Jiang Nutao写道:
我简化了我的问题如下
转换列表
aa = [0x12,0x34,0x56,0x78]
进入
[0x34,0x12,0x78,0x56]
如何快速完成?我真实的名单很大。
非常感谢。
Jason
Jiang Nutao写道:
我简化了下面的问题
转换列表
aa = [0x12,0x34,0x56,0x78]
进入
[0x34,0x12,0x78,0x56]
如何快速完成?我的真实清单很大。
非常感谢。
Jason
这里''简单而且可能足够快的方式(但它不能正常工作
奇数长度列表):
def rev(n):
i = iter(n)
而True:
a = i.next()
收益率i.next()
收益a
使用示例:
r =范围(24)
打印列表(rev(r))
如果你的列表来自二进制(str)数据,并且你正在处理
endianness,我使用struct更快的方式。
和平,
~Simon
Jiang Nutao:
转换列表
aa = [0x12,0x34,0x56,0x78]
into
[0x34,0x12,0x78,0x56]
如何快速完成?我的真实清单很大。
请注意:
>> a =范围(6)
a
[0,1,2,3,4 ,5]
>> a [:: 2]
[0,2,4]
>> a [1 :: 2]
[1,3,5]
所以你可以这样做:
> ;> a [:: 2],a [1 :: 2] = a [1 :: 2],a [:: 2]
a
[1,0,3,2,5,4]
再见,
bearophile >
Hi,
I simplify my problem like below
To convert list
aa = [0x12, 0x34, 0x56, 0x78]
into
[0x34, 0x12, 0x78, 0x56]
How to do it fast? My real list is huge.
Thanks a lot.
Jason
解决方案for i in xrange(0, len(your_list), 2):
your_list[i], your_list[i + 1] = your_list[i + 1], your_list[i]
Jiang Nutao wrote:Hi,
I simplify my problem like below
To convert list
aa = [0x12, 0x34, 0x56, 0x78]
into
[0x34, 0x12, 0x78, 0x56]
How to do it fast? My real list is huge.
Thanks a lot.
Jason
Jiang Nutao wrote:Hi,
I simplify my problem like below
To convert list
aa = [0x12, 0x34, 0x56, 0x78]
into
[0x34, 0x12, 0x78, 0x56]
How to do it fast? My real list is huge.
Thanks a lot.
JasonHere''s simple and probably fast enough way (but it won''t work right on
odd length lists):
def rev(n):
i = iter(n)
while True:
a = i.next()
yield i.next()
yield a
Example of use:
r = range(24)
print list(rev(r))
If your list comes from binary (str) data, and you''re dealing with
endianness, I smell a faster way using struct.
Peace,
~Simon
Jiang Nutao:To convert list
aa = [0x12, 0x34, 0x56, 0x78]
into
[0x34, 0x12, 0x78, 0x56]
How to do it fast? My real list is huge.Note that:
>>a = range(6)
a
[0, 1, 2, 3, 4, 5]
>>a[::2]
[0, 2, 4]
>>a[1::2]
[1, 3, 5]
So you can do:
>>a[::2], a[1::2] = a[1::2], a[::2]
a
[1, 0, 3, 2, 5, 4]
Bye,
bearophile
这篇关于交换列表中的数字项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!