所以我正在编写一个带有2个列表并切换其值的函数.我将有2个清单
list_one = [1, 2, 3]
list_two = [4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
我想切换他们的价值观.输出应该看起来像
#Before swap
list_one: [1, 2, 3]
list_two: [4, 5, 6]
#After swap
list_one: [4, 5, 6]
list_two: [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
这是一个小小的学校作业,所以我想使用一个for循环,它就是我所说的.
到目前为止,这是我的代码:
def swap_lists(first, second):
if len(first) != len(second):
print "Lengths must be equal!"
return
first == second
print second
list_one = [1, 2, 3]
list_two = [4, 5, 6]
print "Before swap"
print "list_one: " + str(list_one)
print "list_two: " + str(list_two)
swap_lists(list_one, list_two)
print "After swap"
print "list_one: " + str(list_one)
print "list_two: " + str(list_two)
Run Code Online (Sandbox Code Playgroud)
我也想通了
first,second = second,first
Run Code Online (Sandbox Code Playgroud)
不起作用.
就for循环而言,您可以逐个元素地交换
for i in range(len(list_one)):
list_one[i], list_two[i] = list_two[i], list_one[i]
Run Code Online (Sandbox Code Playgroud)
更简洁地说,您可以交换整个列表
list_one, list_two = list_two, list_one
Run Code Online (Sandbox Code Playgroud)
如果一个列表比另一个列表长,则在上述任一方法中都需要额外的逻辑