简体   繁体   English

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

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

I am trying to make a program that replaces numbers in one list (from the user) with words (also from the user).我正在尝试制作一个程序,用单词(也来自用户)替换一个列表(来自用户)中的数字。 For example 1 = "c", 2 = "z", 3 = "p".例如 1 = "c", 2 = "z", 3 = "p"。

This is what I have done so far:这是我到目前为止所做的:

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

I`m not sure on what to do on the last couple of lines as no matter what I do it ends up just not working as intended.我不确定在最后几行要做什么,因为无论我做什么,最终都无法按预期工作。

I`m trying to do something along the lines of: if numbers(z) is equal to wordlist.index then replace numbers(p) with wordlist.index(p) (with p being equal to the number of the index of the list of words (as long as all the words In the wordslist are different) and the number of the values in the "numbers"list (for example numbers = [1,2,3,1,4,5] then z would be the first and fourth value in this list))我正在尝试做一些事情:如果 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)

Output :输出 :

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

If you want only unique values then instead of using list,use set如果您只想要唯一值,而不是使用列表,请使用 set

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

If you want to take use input如果你想使用输入

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)

Input:输入:

apple orange banana
1 2 1

Output:输出:

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

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

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