Python 尝试按顺序返回值和单词的列表

Python 尝试按顺序返回值和单词的列表,python,Python,我试图按顺序返回用户输入的单词和数字列表,但当我运行模块时,输入单词和值,它将按顺序打印术语和值,而不打印任何值 dictionary = [] value = [] addterm1 = raw_input("Enter a term you would like to add to the dictionary: ") addterm2 = raw_input("Enter a term you would like to add to the dictionary: ") addter

我试图按顺序返回用户输入的单词和数字列表,但当我运行模块时,输入单词和值,它将按顺序打印术语和值,而不打印任何值

dictionary = []

value = []

addterm1 = raw_input("Enter a term you would like to add to the dictionary: ")
addterm2 = raw_input("Enter a term you would like to add to the dictionary: ")
addterm3 = raw_input("Enter a term you would like to add to the dictionary: ")

addvalue1 = float(raw_input("Enter a number you would like to add to the set of values: "))
addvalue2 = float(raw_input("Enter a number you would like to add to the set of values: "))
addvalue3 = float(raw_input("Enter a number you would like to add to the set of values: "))

dictionary.append(addterm1)
dictionary.append(addterm2)
dictionary.append(addterm3)

value.append(addvalue1)
value.append(addvalue2)
value.append(addvalue3)

def reverseLookup(dictionary, value):

    print dictionary.sort()

    print value.sort()


if __name__ == '__main__':
    reverseLookup(dictionary, value)
.sort()
方法不会
返回已排序的iterable,而是就地排序。您需要
排序
,然后
打印

dictionary.sort()
print(dictionary)
或者,使用
sorted()
函数,该函数返回排序后的iterable:

print(sorted(dictionary))
是就地方法,因此总是返回
None
。因此,对它的任何调用都应该放在他们自己的线路上

如果仍要使用
list.sort
,则可以这样编写代码:

def reverseLookup(dictionary, value):
    dictionary.sort()
    value.sort()
    print dictionary
    print value
或者,您可以使用:


此外,您可能希望为
字典选择不同的名称,因为它是一个列表,而不是一个列表。

有两个不同的函数。和(您现在正在使用的)

sorted()
返回已排序的列表。例如:

>>> a = [3, 1, 5, 2, 4]
>>> print sorted(a)
[1, 2, 3, 4, 5]
这可能就是你想要做的

list.sort()
的功能与此完全相同。但是,它不会返回排序列表。相反,它会对列表进行适当的排序

python中的大多数就地函数都返回
None
。所以你要做的是:

>>> a = [3, 1, 5, 2, 4]
>>> a = a.sort()
>>> print a
None

要修复代码,您可以执行
print sorted(dictionary)
print sorted(values)

您可以使用循环将其缩短,例如
用于范围(3):value.append(float(raw_input(…)
。在连续行上重复相同的字符串是绝对免费的。
>>> a = [3, 1, 5, 2, 4]
>>> a.sort()
>>> print a
[1, 2, 3, 4, 5]
>>> a = [3, 1, 5, 2, 4]
>>> a = a.sort()
>>> print a
None