【发布时间】:2018-05-19 21:15:12
【问题描述】:
所以我正在为班级做一个练习,我需要打印出哪些字符出现以及它们出现在哪里。我使用以下代码做到了这一点:
def letterInString(string):
index = 0
pos = ""
stringList = list(string)
positions = []
counter = 0
occurences = {}
for l in string:
for x in string:
if x == l:
counter += 1
positions.append(stringList.index(x))
for item in positions:
if index == 0:
pos = str(positions[index])
index += 1
else:
pos = pos + "," + str(positions[index])
index += 1
occurences[l.upper()] = str(counter) + "(" + pos + ")"
index = 0
positions = []
counter = 0
for key,value in occurences.items():
print(key + ": " + str(value))
letterInString("hello")
该代码对没有重复的单词工作得很好,但是当有重复时,它不知道要索引哪个字母。我代码的最后一部分只是为了测试某些情况。请帮忙!!!
感谢任何帮助!
【问题讨论】:
-
你可以这样做
[ {"char": i,"position": c} for i,c in enumerate(s)]where s="hello" -
对,这基本上就是我的答案
标签: python string list indexing