用输入替换列表中大于100的某些对象,然后

我必须将列表的第5个元素乘以2,然后将结果放入新列表中,然后将两个列表合并。


我什至不知道如何启动它,更不用说继续了。


编辑

休息一会儿,这与我使用0知识所做的一样多。


L = [ 10, 2, 56, 33, 23, 1, 564, 32, 122, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 254 ]


x = int(input("Insert number here: "))


for i in range(0, int(len(L))):

    if L[i] > 100:

       L.pop(i)    

       L.insert(i, x)

       print(L)


翻翻过去那场雪
浏览 164回答 3
3回答

慕标5832272

根据您最清楚的解释,这是我的建议。我希望它符合您的期望:L = [ 10, 2, 56, 33, 23, 1, 564, 32, 122, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 254 ]# Ask for user inputmyInput = int(input("Enter a number: "))  # ex: I entered 5# Replace the numbers in L that are greater than 100 with the input numberL = [myInput if i > 100 else i for i in L]print(L) # ex: [10, 2, 56, 33, 23, 1, 5, 32, 5, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 5]# Take every 5th element of L, multiply it by 2 and place the results into a brand new list KK = [value*2 for i,value in enumerate(L,1) if i % 5 == 0]print(K) # ex: [46, 84, 6, 18]# Merge L and K into LKLK = L + Kprint(LK) # ex: [10, 2, 56, 33, 23, 1, 5, 32, 5, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 5, 46, 84, 6, 18]

慕的地10843

根据以上评论,这是您的问题的解决方案。如果这不是您想要的,请告诉我,我会相应地进行更新。我在这里使用列表推导。我曾经(i+1)%5访问过第5个索引,因为该索引从0python开始。L = [ 10, 2, 56, 33, 23, 1, 564, 32, 122, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 254 ]x = int(input("Insert number here: "))L1 = [x if i > 100 else i for i in L]L2 = [2*j if (i+1)%5==0 else j for i, j in enumerate(L1)]L_output = L1 + L2print (L1)print (L2)print (L_output)输出Insert number here: 6[10, 2, 56, 33, 23, 1, 6, 32, 6, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 6][10, 2, 56, 33, 46, 1, 4, 32, 4, 84, 3, 4, 2, 1, 6, 2, 1, 54, 5, 18, 1, 65, 4][10, 2, 56, 33, 23, 1, 6, 32, 6, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 6, 10, 2, 56, 33, 46, 1, 4, 32, 4, 84, 3, 4, 2, 1, 6, 2, 1, 54, 5, 18, 1, 65, 4]

海绵宝宝撒

也许这样可以帮助:l1 = range(100)l2 = [l1[x]*2  if x%5==4 else l1[x] for x in range(len(l1)) ]print(l2)它仅修改每五个元素:因此,这些元素在第4、9、14等位置。(因此,x模5等于4)其他元素保持原样。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python