Dar*_*nes 2 python list while-loop
Python /编程新手,尝试弄清楚这个while循环的内容.首先是代码:
var_list = []
split_string = "pink penguins,green shirts,blue jeans,fried tasty chicken,old-style boots"
def create_variations(split_string):
init_list = split_string.split(',')
first_element = init_list[0]
# change first element of list to prepare for while loop iterations
popped = init_list.pop()
added = init_list.insert(0, popped)
while init_list[0] != first_element:
popped = init_list.pop()
added = init_list.insert(0, popped)
print init_list # prints as expected, with popped element inserted to index[0] on each iteration
var_list.append(init_list) # keeps appending the same 'init_list' as defined on line 5, not those altered in the loop!
print var_list
create_variations(split_string)
Run Code Online (Sandbox Code Playgroud)
我的目标是创建所有变体init_list,意味着索引被旋转,以便每个索引只是第一次.然后将这些变体附加到另一个列表中,该列表var_list在此代码中.
但是,我没有得到我期望从while循环得到的结果.在while循环中,这段代码print init_list实际上打印出我想要的变化; 但是下一行代码var_list.append(init_list)并未附加这些变体.而是将init_list第5行上创建的as重复附加到var_list.
这里发生了什么?我怎样才能init_list将while循环中创建的不同变体附加到var_list.
输出我期望var_list:
[['fried tasty chicken', 'old-style boots', 'pink penguins', 'green shirts', 'blue jeans'],
['blue jeans', 'fried tasty chicken', 'old-style boots', 'pink penguins', 'green shirts'],
['green shirts', 'blue jeans', 'fried tasty chicken', 'old-style boots', 'pink penguins'],
['pink penguins', 'green shirts', 'blue jeans', 'fried tasty chicken', 'old-style boots']]
Run Code Online (Sandbox Code Playgroud)
这里有一些代码能够以更简单的方式完成我认为你想要的东西:
variations = []
items = [1,2,3,4,5]
for i in range(len(items)):
v = items[i:] + items[:i]
variations.append(v)
print variations
Run Code Online (Sandbox Code Playgroud)
输出:
[[1, 2, 3, 4, 5], [2, 3, 4, 5, 1], [3, 4, 5, 1, 2], [4, 5, 1, 2, 3], [5, 1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)
或者您可以使用这个简单的生成器:
(items[i:] + items[:i] for i in range(len(items)))
Run Code Online (Sandbox Code Playgroud)