Python 列表返回无,忽略值
我试图返回字母的值和位置。以普通for循环的形式运行这个程序很好。当我把它变成一个函数的时候,它开始看起来不稳定了 下面是它的输出:Python 列表返回无,忽略值,python,list,dictionary,Python,List,Dictionary,我试图返回字母的值和位置。以普通for循环的形式运行这个程序很好。当我把它变成一个函数的时候,它开始看起来不稳定了 下面是它的输出: dict = {'a': 1, 'b': 2 ... 'z': 26} list1 = [] list2 = [] def plot(word): counter = 0 for i in word: y = dict.get(i) list1.append(y) #keeps printing None for
dict = {'a': 1, 'b': 2 ... 'z': 26}
list1 = []
list2 = []
def plot(word):
counter = 0
for i in word:
y = dict.get(i)
list1.append(y) #keeps printing None for the first letters
counter += 1
x = counter
list2.append(x)
print list1
print list2
r = zip(list1, list2)
print r
t = raw_input('Enter word: ')
Enter word: Hello
plot(t)
Output:
[None, None, 5, 12, 12, 15]
[1, 2, 3, 4, 5]
[(None, 1), (None, 2), (5, 3), (12, 4), (12, 5)]
我认为问题在于你正在试图绘制一个大写字母。我只需将for循环更改为遍历小写
for i in word.lower():
y = dict.get(i)
list1.append(y) #keeps printing None for the first letters
counter += 1
x = counter
list2.append(x)
如果
dict.get(i)
是None
,则i
不是dict
中的键<代码>'h'在里面,但是'h'
在里面吗?另外,不要给自己的字典命名dict
。我正在寻找的输出是[(8,1),(5,2),(12,3),(12,4),(15,5)]。另外,请注意列表1有六个元素,即使“Hello”只有五个字母。所以你实际上只漏掉了一封信。尝试对单词使用lower()方法将所有字母转换为小写。然后确保单词前面没有空格(看起来“Hello”前面有空格)。看起来字典中缺少了一些字符。请注意,它们区分大小写d.get(“foo”)
将返回None
,如果字典中不存在密钥。非常感谢!我还发现,它还计算原始输入中冒号后面的额外空间('Enter word:')。当我取下它时,一切都很顺利。