问候Pythonic世界.学习Python 3.3的第4天,我遇到了一个奇怪的属性list.sort.
我创建了一个包含五个元素的列表:四个字符串,中间有一个数字.list.sort由于混合类型,试图开始工作给出了预期的错误:
>>> list = ['b', 'a', 3, 'd', 'c']
>>> list.sort()
Traceback (innermost last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
>>> list
['b', 'a', 3, 'd', 'c']
Run Code Online (Sandbox Code Playgroud)
列表没有变化.
但后来我把数字移到了最后,再次使用了list.sort,得到了这个:
>>> list = ['b', 'a', 'd', 'c', 3]
>>> list.sort()
Traceback (innermost last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
>>> list
['a', 'b', 'c', 'd', 3]
Run Code Online (Sandbox Code Playgroud)
好的,一个错误.但是这个列表已经自行排序,将数字踢到最后.我在这个网站或Langtangen找不到任何解释.这种行为有一些潜在的原因吗?在某些情况下它会有用吗?
这只是我学习Python 3.3的第二天,所以我承认我有很多需要学习的东西.
简而言之,我有两个列表:List1充满奇数,List2充满偶数.它们的长度相同(每个都有五个数字).
我想通过将List1的每个元素与List2中的相同元素组合,并递增计数器来创建包含[1,2,3,4,5,6,...]的List4.我猜想要使用Append.我的问题在于接近结束时的评论.
我还有更多的功能需要学习,但如果有人能提供帮助,我将非常感激.我的程序无疑可以变得更加流畅,但这可以在以后发生.
谢谢!
# Fill list with odd numbers up to 10
a = -1
list1 = []
while a < 10:
a += 2
print (a)
list1.append(a)
print ("a = ", a, "\nList 1 = ", list1)
# Fill list with even numbers up to 10
a = 0
list2 = []
while a < 10:
a += 2
print (a)
list2.append(a)
print ("a = ", a, "\nList2 = ", list2)
#Combine the lists side by …Run Code Online (Sandbox Code Playgroud)