我想在不导入任何模块的情况下混洗列表中的元素。混洗的类型是riffle shuffle。在那里你想要把no。将列表中的元素合并为两个元素,然后交错。
如果有奇怪的不。,那么后半部分应该包含额外的元素。
例如: list = 1,2,3,4,5,6,7
then the final list should look like [1,4,2,5,3,6,7]发布于 2013-11-11 11:59:57
只是为了好玩,一个递归的解决方案:
def interleave(lst1, lst2):
if not lst1:
return lst2
elif not lst2:
return lst1
return lst1[0:1] + interleave(lst2, lst1[1:])在Python2.x中按如下方式使用(在Python3.x中,使用//而不是/):
lst = [1,2,3,4,5,6,7]
interleave(lst[:len(lst)/2], lst[len(lst)/2:])
=> [1, 4, 2, 5, 3, 6, 7]上面的方法适用于任何长度的列表,不管长度是偶数还是奇数。
发布于 2013-11-11 11:37:19
listA = [1,2,3,4,5,6,7,8,9]
listLen = len(listA)/2
listB = listA[:listLen]
listC = listA[listLen:]
listD = []
num = 0
while num < listLen:
if len(listB) >= num:
listD.append(listB[num])
listD.append(listC[num])
num += 1
if len(listA)%2 != 0:
listD.append(listC[num])
print listD在查看了另一个答案后,我还添加了一个递归版本,这是另一个人答案的修订版本,但更容易调用,因为您只需使用单个参数(您试图混洗的列表)调用函数,并且它可以执行其他所有操作:
def interleave(lst):
def interleaveHelper(lst1,lst2):
if not lst1:
return lst2
elif not lst2:
return lst1
return lst1[0:1] + interleaveHelper(lst2, lst1[1:])
return interleaveHelper(lst[:len(lst)/2], lst[len(lst)/2:])当你调用它时,你可以说interleave(list)
发布于 2013-11-11 14:08:38
例如: list = 1,2,3,4,5,6,7那么最终的列表应该是1,4,2,5,3,6,7
这里有一个函数可以可靠地做到这一点:
def riffle(deck):
'''
Shuffle a list like a deck of cards.
i.e. given a list, split with second set have the extra if len is odd
and then interleave, second deck's first item after first deck's first item
and so on. Thus:
riffle([1,2,3,4,5,6,7])
returns [1, 4, 2, 5, 3, 6, 7]
'''
cut = len(deck) // 2 # floor division
deck, second_deck = deck[:cut], deck[cut:]
for index, item in enumerate(second_deck):
insert_index = index*2 + 1
deck.insert(insert_index, item)
return deck为了对它进行单元测试...
import unittest
class RiffleTestCase(unittest.TestCase):
def test_riffle(self):
self.assertEqual(riffle(['a','b','c','d','e']), ['a','c','b','d','e'])
self.assertEqual(riffle([1,2,3,4,5,6,7]), [1,4,2,5,3,6,7])
unittest.main()
----------------------------------------------------------------------
Ran 1 test in 0.000s
OKhttps://stackoverflow.com/questions/19898138
复制相似问题