[英]Swap all elements in a list in python 3.4
假设我的清单如下:
myList = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']
我希望结果看起来像这样:
One, Eight, Two, Seven, Three, Six, Four, Five
最简单的方法是什么?
from collections import deque
myList = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']
def swap(items):
items = deque(items)
while items:
yield items.popleft()
try:
yield items.pop()
except IndexError:
pass
print list(swap(myList))
编辑:现在非破坏性和应付不均匀的长度列表
编辑:使用双端队列以便其内存高效
如果我理解得很好,这将创建一个具有所需顺序的新列表。
myList = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']
i = 0
new_list = []
while i < len(myList)/2:
new_list.append(myList[i])
i += 1
new_list.append(myList[-i])
print ', '.join(new_list)
切片:
>>> result = list(myList)
>>> result[::2] = myList[:4]
>>> result[::-2] = myList[4:]
>>> result
['One', 'Eight', 'Two', 'Seven', 'Three', 'Six', 'Four', 'Five']
第一个赋值可以由创建正确长度列表的任何内容替换,然后myList的前4个元素成为结果的第二个元素,而后4个元素则是第二个从末尾倒数的元素。
当然,如果您想要不带括号的输出:
>>> print(', '.join(result))
One, Eight, Two, Seven, Three, Six, Four, Five
如果您不介意列出原始列表,则可以在一行中完成所有操作:
>>> myList[::2], myList[::-2] = myList[:4], myList[4:]
>>> myList
['One', 'Eight', 'Two', 'Seven', 'Three', 'Six', 'Four', 'Five']
myList = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']
z=[x for x in myList if myList.index(x)>=len(myList)/2]
print zip(myList,reversed(z))
你可以试试看
如果需要单线,可以查看:
final = [el for zipped in zip(lst[:4], reversed(lst[4:])) for el in zipped]
这是解决不需要异常处理的问题的两种方法,将输入列表加载到备用数据结构中只是为了销毁它。 他们通过计算列表的中点并清楚地知道自己是否在处理奇数列表来做到这一点:
def interleave(l):
"""
Non-destructive front-and-back iterleave of list items.
"""
midpoint, odd_length = divmod(len(l), 2)
for i in range(midpoint):
yield l[i]
yield l[-i-1]
if odd_length:
yield l[midpoint]
要么:
def interleave2(l):
"""
Non-destructive front-and-back iterleave of list items.
Uses zip and reversed generators and list slicing.
Arguably more "Pythonic," but depends on more in-flight
infrastructure and consumes more memory.
"""
midpoint, odd_length = divmod(len(l), 2)
for front, back in zip(l[:midpoint], reversed(l[midpoint:])):
yield front
yield back
if odd_length:
yield l[midpoint]
以下是一些即席测试工具,用于确认结果正确:
myList = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']
myListAnswer = ['One', 'Eight', 'Two', 'Seven', 'Three', 'Six', 'Four', 'Five']
answers = {}
for algorithm in [interleave, interleave2]:
print()
print(algorithm.__name__, "\n", "=" * len(algorithm.__name__), "\n")
# test the simple case
assert list(algorithm(myList)) == myListAnswer
# test a number of list sizes
for j in range(11):
# run algorithm and show inputs and outputs
l = list(range(j))
print("size:", j)
print("list:", l)
answer = list(algorithm(l))
print("answer:", answer)
# check assertions
prev_answer = answers.setdefault(j, answer)
assert len(l) == len(answer)
assert l == sorted(answer)
assert answer == prev_answer
print("--")
这样产生:
interleave
==========
size: 0
list: []
answer: []
--
size: 1
list: [0]
answer: [0]
--
size: 2
list: [0, 1]
answer: [0, 1]
--
size: 3
list: [0, 1, 2]
answer: [0, 2, 1]
--
size: 4
list: [0, 1, 2, 3]
answer: [0, 3, 1, 2]
--
size: 5
list: [0, 1, 2, 3, 4]
answer: [0, 4, 1, 3, 2]
--
size: 6
list: [0, 1, 2, 3, 4, 5]
answer: [0, 5, 1, 4, 2, 3]
--
size: 7
list: [0, 1, 2, 3, 4, 5, 6]
answer: [0, 6, 1, 5, 2, 4, 3]
--
size: 8
list: [0, 1, 2, 3, 4, 5, 6, 7]
answer: [0, 7, 1, 6, 2, 5, 3, 4]
--
size: 9
list: [0, 1, 2, 3, 4, 5, 6, 7, 8]
answer: [0, 8, 1, 7, 2, 6, 3, 5, 4]
--
size: 10
list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
answer: [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
--
# ...and continues on with similar output for interleave2 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.