如何使用其他列表中的项替换列表中的项目

时间:2017-01-21 17:40:25

标签: python python-3.x

我正在尝试制作一个程序,用一个单词(也来自用户)替换一个列表中的数字(来自用户)。例如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)替换数字(p)(p等于单词列表索引的数量(只要单词列表中的所有单词)是不同的)和"数字"列表中的值的数量(例如数字= [1,2,3,1,4,5],那么z将是此列表中的第一个和第四个值))

1 个答案:

答案 0 :(得分:0)

    let b1 = UIButton()
    b1.translatesAutoresizingMaskIntoConstraints = false
    b1.backgroundColor = .green
    b1.setTitle("Button1", for: .normal)
    b1.setTitleColor(.black, for: .normal)

    let b2 = UIButton()
    b2.translatesAutoresizingMaskIntoConstraints = false
    b2.backgroundColor = .yellow
    b2.setTitle("Button2", for: .normal)
    b2.setTitleColor(.black, for: .normal)

    self.view.addSubview(b1)
    self.view.addSubview(b2)

    NSLayoutConstraint.activate([
        b1.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50),
        b2.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50),

        b1.leadingAnchor.constraint(equalTo:self.view.leadingAnchor),
        b2.leadingAnchor.constraint(equalTo:b1.trailingAnchor),

        b1.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.5),
        b2.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.5),

    ])

输出:

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)

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

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

如果您想使用输入

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

输入:

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