一次将整数列表输入到程序1中,例如:
[1, 3, 1, 4, 4, 3, 1]
任务:
打印包含与给定列表完全相同的数字的列表,
但必须重新排列,以使每3个紧随其后的是4个。3不得移动索引位置,但其他所有数字都可以移动。
该示例的输出应为:
[1, 3, 4, 1, 1, 3, 4]
到目前为止,我的代码只能完成规则1和2。如何修改我的代码以适应这一要求?
newList=[]
n=0
numCount= int(input())
while True:
try:
n = int(input())
except:
break
if len(newList) !=(numCount):
if n == 3:
newList.append(3)
newList.append(4)
else:
newList.append(n)
print(newList)
答案 0 :(得分:3)
我建议您首先获取输入列表中3和4的所有索引,然后将3之后的每个元素与4交换。它给出以下代码,该代码很短并且易于阅读:
a = [1, 3, 1, 4, 4, 3, 1]
# Get the indexes of 3 and 4 in the list
indexesOf3 = [i for i,elem in enumerate(a) if elem == 3]
indexesOf4 = [i for i,elem in enumerate(a) if elem == 4]
# Swap each element following a 3 with a 4
for i3,i4 in zip(indexesOf3,indexesOf4):
a[i3+1], a[i4] = a[i4], a[i3+1]
print(a)
# [1, 3, 4, 1, 1, 3, 4]
注意:此代码示例修改了输入列表,但显然可以轻松地将其更新为返回新列表并保持输入列表不变的函数。
答案 1 :(得分:0)
这里有一个功能完全可以做到:
score1 = float(input("Test number {}: ".format(s+1)))
如果我们用您的示例对其进行测试,则会得到:
def arrange_list(my_list):
# Copy the whole list
arranged_list=myList.copy()
# Find the all 4s
index_of_4s=[i for i, x in enumerate(arranged_list) if x == 4]
next_4=0
# Loop over the whole list
for i in range(len(arrangedList)):
if(arrangedList[i]==3): # We only care about 3s
# We swap the previously found 4 with a 1
arranged_list[index_of_4s[next_4]]=arranged_list[i+1]
arranged_list[i+1]=4
# We target the next 4
next_4=next_4+1
return arranged_list
答案 2 :(得分:0)
您所提出的问题的定义不是很好,也没有考虑到丢失情况。这段代码的工作非常简单,其想法是创建一个新列表。
-查找3在输入中的位置
-将3放置在新列表中,然后再放置4
-放置其余元素。
{
"name":"John",
"age":30,
123:[ "Ford", "BMW", "Fiat" ]
在具有单循环的更紧凑版本中,它提供:
input_list = [1, 3, 1, 4, 4, 3, 1]
# Check the number of 3 and 4
n3 = input_list.count(3)
n4 = input_list.count(4)
if n3 > n4:
for i in range(n3-n4):
input_list.append(4)
elif n4 > n3:
for i in range(n4-n3):
input_list.append(3)
# Now let's look at the order. The 3 should not move and must be followed by a 4.
# Easy way, create a new list.
output_list = [None for i in range(len(input_list))]
# Then I'm using numpy to go faster but the idea is just to extract the ids are which the 3 are placed.
import numpy as np
# Place the 3 and the 4
for elt_3 in np.where(np.asarray(input_list) == 3)[0]:
output_list[elt_3] = 3
output_list[elt_3+1] = 4 # Must be sure that the input_list does not end by a 3 !!!
# Then we don't care of the position for the other numbers.
other_numbers = [x for x in input_list if x != 3 and x != 4]
for i, elt in enumerate(output_list):
if elt is None:
output_list[i] = other_numbers[0]
del other_numbers[0]
print (output_list)