繁体   English   中英

将列表中的元素从str转换为int

[英]Converting elements of a list from str to int

我正在开发一个包含两个列表的程序:一个只是随机排列的数字1-5,另一个是另存为不同元素的五个单词。 基本上,我希望能够按照第一个列表的随机顺序打印出单词。 我试过了:

order = ["2","5","4","1","3"]
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
for i in range (0,5):
    print(words[order])

它只是说“ TypeError: list indices must be integers, not list ”。 谁能帮我?

这里有两个问题:

  1. 您无需获取order的元素,只需将整个列表作为索引传递;
  2. 如错误所示,您应该将字符串'2'转换为整数2

我们可以为此使用int(..) 现在出现了一个新问题:列表具有从零开始的索引,而列表中的索引是从一开始的。 但是,我们可以从中减去一个。

这导致以下方法:

for i in order:
    print(words[int(i)-1])

更正代码如下所示:

order = ["1","2","3","4","5"]
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
for i in range(0,5):
    print(words[int(order[i])])

但这远不是一个干净的解决方案。 您对index es的了解太多了。

一个更好的方法是这样的:

for x in order:
    print(words[int(x)-1])

综上所述,您所做的工作没有任何随机性 考虑使用random.shuffle() 像这样:

from random import shuffle

order = ["1","2","3","4","5"]
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
shuffle(order)  # the shuffling is done in-place

for i in [int(c)-1 for c in order]:
    print(words[i])

# prints
Carrot
Dragonfly
Education
Boat
Apple
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
# 1 #
for _ in range(11):
    print(words[random.randrange(0, len(words))])
# 2 #
print("Before shuffle: ",words);random.shuffle(words);print("After shuffle: ",words)
# 3 #
print("Choose 1 random sample",random.sample(words, 1))

我不知道你的目标是什么,但这就是我的想法。 同样,您也不需要将它们作为str存储在“ order”列表中。 您可以有一个整数列表,无需转换即可使用它。 如:order = [1,2,3,4,5]

希望我的回答对您有所帮助。

暂无
暂无

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

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