我试图根据这个例子进行信件排序:
输入:
people enjoy programming
输出:
[(set(['e', 'o']), set(['l']), set(['p'])),
(set(['e', 'o']), set(['j']), set(['n', 'y'])),
(set(['o', 'a', 'i']), set(['g', 'm']), set(['p', 'r', 'n']))]
所以这是我的代码:
lista=[[[0],[0],[0]],[[0],[0],[0]],[[0],[0],[0]]]
x=raw_input('please enter 3 words: ')
words=x.split()
if len(words)!=3:
print('error!!! enter 3 words ')
else:
i=0
c=0
while i<3:
for m in range(len(words[i])):
if words[i][m] in ['a','e','i','o','u']:
lista.insert([i][0][c],words[i][m])
lista.insert([i][0][-1],0)
c=c+1
elif words[i][m] in ['b','c','d','f','g','h','j','k','l','m']:
lista.insert([i][1][c],words[i][m])
lista.insert([i][1][-1],0)
c=c+1
else:
lista.insert([i][2][c],words[i][m])
lista.insert([i][2][-1],0)
c=c+1
i=i+1
lista=(set(lista[1][1],lista[1][2],lista[1][3],lista[2][1],lista[2][2],lista[2][3],lista[3][1],lista[3][2],lista[3][3]))
lista=(tuple(lista[1],lista[2],lista[3]))
print lista
当我尝试运行它时,我收到此错误:
Traceback(最近一次调用最后一次):文件“C:/Python27/ex7.py”,第22行,in lista.insert([i] [2] [c],words [i] [m])IndexError:列表索引超出范围
有人看到我做错了什么?
答案 0 :(得分:1)
我不认为行lista.insert([i][1][c],words[i][m])
(以及与其他索引类似的行)执行您似乎想要的操作。在尝试评估words[i][m]
时,您收到的错误不是将lista[i][1][c]
插入[i][1][c]
。该子表达式创建一个元素列表([i]
,然后尝试访问索引1
的值,这不起作用。
我想你可能想要使用像lista[i][1].append(words[i][m])
这样的东西。
但是,如果直接迭代列表和字符串,而不是使用range
和索引,则会更容易:
output = []
for word in words:
vowels = set()
consonants1 = set()
consonants2 = set()
for character in word:
if character in "aeiou":
vowels.add(character)
elif character in "bcdfghjklm":
consonants1.add(character)
else:
consonants2.add(character)
output.append([vowels, consonants1, consonants2])
答案 1 :(得分:0)
words = []
output = []
desired_output = [(set(['e', 'o']), set(['l']), set(['p'])), (set(['e', 'o']), set(['j']), set(['n', 'y'])),
(set(['o', 'a', 'i']), set(['g', 'm']), set(['p', 'r', 'n']))]
while True:
# words = raw_input('please enter 3 words: ').split()
words = "people enjoy programming".split()
if len(words) != 3:
print('error!!! enter 3 words ')
else:
break
for word in words:
vow = set()
con1 = set()
con2 = set()
for char in word:
if char in "aeiou":
vow.add(char)
elif char in "bcdfghjklm":
con1.add(char)
else:
con2.add(char)
output.append([vow, con1, con2])
print output
print desired_output
输出:
[[set(['e', 'o']), set(['l']), set(['p'])], [set(['e', 'o']), set(['j']), set(['y', 'n'])], [set(['a', 'i', 'o']), set(['m', 'g']), set(['p', 'r', 'n'])]]
[(set(['e', 'o']), set(['l']), set(['p'])), (set(['e', 'o']), set(['j']), set(['y', 'n'])), (set(['a', 'i', 'o']), set(['m', 'g']), set(['p', 'r', 'n']))]
将words = "people enjoy programming".split()
替换为其上方的{{1}}以使其具有交互性。
使用范围和索引来访问项目在已经具有过去编程经验(可能是C ++?)的人中非常常见,在Python中大多数事情都是可迭代的。你可以在列表上使用for循环,它将返回每个项目,你可以迭代一个字符串,它将返回每个字符。