繁体   English   中英

如何用另一个列表中的项目替换列表中的项目

[英]How to replace items in a list with items from another list

我正在尝试制作一个程序,用单词(也来自用户)替换一个列表(来自用户)中的数字。 例如 1 = "c", 2 = "z", 3 = "p"。

这是我到目前为止所做的:

wordlist = [None]
numbers = [0]
wordlist = input()
numbers = input()
wordlist.remove(None)
numbers.remove(0)
for numbers,item in enumerate(numbers):
    numbers.index(z) = wordlist.index
    z = z + 1

我不确定在最后几行要做什么,因为无论我做什么,最终都无法按预期工作。

我正在尝试做一些事情:如果 numbers(z) 等于 wordlist.index 然后用 wordlist.index(p) 替换 numbers(p)(p 等于列表的索引号单词(只要单词列表中的所有单词都不同)和“数字”列表中的值的数量(例如 numbers = [1,2,3,1,4,5] 那么 z 将是此列表中的第一个和第四个值))

wordlist=['apple','orange','banana']
numbers=[1,2,1]
ans=[]

for i in numbers:
    if i<len(wordlist):     #checks if value in numbers is below len of wordlist 
        ans.append(wordlist[i])

print(ans)

输出 :

['orange', 'banana', 'orange']

如果您只想要唯一值,而不是使用列表,请使用 set

================================

如果你想使用输入

wordlist = raw_input().split(' ')         #splits sentence into words using space as delimitor
numbers = [int(x) for x in raw_input().split()]    #int(x) is use for casting input string into integer type

ans=[]

for i in numbers:
    if i<len(wordlist):     #checks if value in numbers is below len of wordlist 
        ans.append(wordlist[i])

print(ans)

输入:

apple orange banana
1 2 1

输出:

['orange', 'banana', 'orange']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM