2

我有这个

import random 

a = random.randint(1,100) 
b = random.randint(1,100) 
c = random.randint(1,100) 
d = random.randint(1,100) 
e = random.randint(1,100) 

print "The numbers are a:",a,"b:",b,"c:",c,"d:",d,"and e:",e 
print "The numbers in ascending order:" 
list1=[a,b,c,d,e]
list1.sort(key=int)
print a
print b
print c
print d
print e`

但我无法理解我想为 ae 打印新值而不是旧值

4

6 回答 6

3

遍历list1并打印每个值:

for number in list1:
    print number
于 2013-09-30T08:45:31.277 回答
2

当您对列表进行排序时,您分配的原始变量不会改变,只有列表的内容会改变。

您可以重新分配排序列表中的变量:

list1=[a,b,c,d,e]
list1.sort(key=int)
a, b, c, d, e = list1

print a
print b
print c
print d
print e
于 2013-09-30T08:48:08.103 回答
1

这有效

import random 

a = random.randint(1,100) 
b = random.randint(1,100) 
c = random.randint(1,100) 
d = random.randint(1,100) 
e = random.randint(1,100) 

print "The numbers are a:",a,"b:",b,"c:",c,"d:",d,"and e:",e 
print "The numbers in ascending order:" 
list1=[a,b,c,d,e]
list1.sort(key=int)

for item in list1:
    print item
于 2013-09-30T08:50:08.350 回答
1
import random 

a = random.randint(1,100) 
b = random.randint(1,100) 
c = random.randint(1,100) 
d = random.randint(1,100) 
e = random.randint(1,100) 

print "The numbers are a:",a,"b:",b,"c:",c,"d:",d,"and e:",e 
print "The numbers in ascending order:" 
list1=[a,b,c,d,e]
list1.sort(key=int)
for item in list1:
    print(str(item) + '\n')

你的观念有问题。是的,a,b,c,d,e 是由 random.randint() 创建的。当您对list1 进行排序时,a,b,c,d,e不会因list1 的变化而改变。a,b,c,d,e因为在 list1 中,只有从内部复制的值,而不是a,b,c,d,e它们本身。所以你不能通过改变list1来改变a、b、c、d、e的值。

于 2013-09-30T10:09:15.420 回答
1

通过创建和排序 list1,您可以更改列表的内容,而不是实际的变量 a、b、c、d 和 e。如果您希望 python 打印“新值”,则必须打印 list1。

import random 

a = random.randint(1,100) 
b = random.randint(1,100) 
c = random.randint(1,100) 
d = random.randint(1,100) 
e = random.randint(1,100) 

print "The numbers are a:",a,"b:",b,"c:",c,"d:",d,"and e:",e 
print "The numbers in ascending order:" 
list1=[a,b,c,d,e]
list1.sort(key=int)

for num in list1:
    print num
于 2013-09-30T11:02:08.627 回答
1

您将变量的编号放入列表中list1。如果对列表进行排序,则不会更改ato的值e

如果你想打印它们排序迭代列表并打印所有元素,然后它们被排序。

for current in list1:
    print current
于 2013-09-30T08:46:55.403 回答