我正在尝试熟悉python,我一直在将一些C#代码转换为python而且我遇到了一个我无法弄清楚的错误,我得到的“索引超出范围”错误,这是我的python代码:
import random
myString = raw_input("Input: ")
words = myString.split(" ")
wordList = list()
for word in words:
wordList.append(word)
wordChoice = 0;
myStringRandomized = "";
while len(wordList) != 0:
wordChoice = random.randint(0, len(wordList))
myStringRandomized += wordList[wordChoice] + " "
del wordList[wordChoice]
print("Characters: " + str(len(myString)))
print("Words: " + str(len(myString.split(" "))))
print("Uppercase: " + myString.upper())
print("Lowercase: " + myString.lower())
print("Randomized: " + myStringRandomized)
C#中的等效工作:
static void Main(string[] args)
{
Console.Write("Input: ");
string myString = Console.ReadLine();
string[] words = myString.Split(' ');
List<string> wordList = new List<string>();
foreach (string word in words)
wordList.Add(word);
Random random = new Random();
int wordChoice = 0;
string myStringRandomized = "";
while (wordList.Count != 0)
{
wordChoice = random.Next(0, wordList.Count);
myStringRandomized += wordList[wordChoice] + " ";
wordList.Remove(wordList[wordChoice]);
}
Console.WriteLine("Characters: " + myString.Length);
Console.WriteLine("Words: " + myString.Split(' ').Length);
Console.WriteLine("Uppercase: " + myString.ToUpper());
Console.WriteLine("Lowercase: " + myString.ToLower());
Console.WriteLine("Randomized: " + myStringRandomized);
Console.ReadKey();
}
如果有人能指出我出错的地方会很棒,非常感谢你!
答案 0 :(得分:4)
根据the documentation,random.randint
可以包含 b
的值(在本例中为len(wordList)
)。相反,您应该使用random.randrange
,这是半开(如range
)而赢了包含stop
值(和{,{ {1}}是默认的0
,您可以将其删除。