猿问

为什么我在 python 中的 len() 代码没有提供正确的字符串长度?

我正在尝试使用 python 编写一个刽子手游戏,但在运行代码时我遇到了获取正确长度的字符串以返回的问题。它将返回诸如['clouds'] 10or之类的东西,['mango'] 9或者['rose'] 8当它实际上应该返回['clouds'] 6and['mango'] 5和时['rose'] 4。


请帮我看看我做错了什么!


这是我写的:


import random


word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']


word = str(random.sample(word_list, 1))


word_len = len(word)


print(word, word_len)


慕桂英4014372
浏览 165回答 2
2回答

慕田峪4524236

random.sample(word_list, 1)返回list像 ["sparkle"] 这样的单个项目,并且您将其转换为str,因此它[""]在单词周围添加,因此单词变为'["sparkle"]'我认为你需要:import randomword_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']word = random.sample(word_list, 1)word_len = len(word[0])print(word, word_len)输出:['sparkle'] 7

桃花长相依

你使用了错误的方法import randomword_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']# return a k length list of unique elements chosen from the population sequence or set# where k is 1, population sequence is word_listprint(random.sample(word_list, 1))# to get random item from list you have to use random.choiceprint(random.choice(word_list))
随时随地看视频慕课网APP

相关分类

Python
我要回答