*****其实我的问题是python如何在跟随不同的python代码段中自动为'i'赋值。
data=[5,1,23,10]
datacount=len(data)
print ('value of datacount is',datacount)
for i in range(datacount-1):
print ('value of i is',i)
for k in range(i,datacount):
print ('value of k is', k,'value of i is', i, 'value of datacount is', datacount)
print(data)
if data[i]>data[k]:
temp=data[i]
data[i],data[k]=data[k],temp
for i in range(datacount):
print(data[i])
结果是:
>>>
('value of datacount is', 4)
('value of i is', 0)
('value of k is', 0, 'value of i is', 0, 'value of datacount is', 4)
[5, 1, 23, 10]
('value of k is', 1, 'value of i is', 0, 'value of datacount is', 4)
[5, 1, 23, 10]
('value of k is', 2, 'value of i is', 0, 'value of datacount is', 4)
[1, 5, 23, 10]
('value of k is', 3, 'value of i is', 0, 'value of datacount is', 4)
[1, 5, 23, 10]
('value of i is', 1)
('value of k is', 1, 'value of i is', 1, 'value of datacount is', 4)
[1, 5, 23, 10]
('value of k is', 2, 'value of i is', 1, 'value of datacount is', 4)
[1, 5, 23, 10]
('value of k is', 3, 'value of i is', 1, 'value of datacount is', 4)
[1, 5, 23, 10]
('value of i is', 2)
('value of k is', 2, 'value of i is', 2, 'value of datacount is', 4)
[1, 5, 23, 10]
('value of k is', 3, 'value of i is', 2, 'value of datacount is', 4)
[1, 5, 23, 10]
1
5
10
23
>>>
考虑以下代码
data = [5,1,23,10,-3]
def fun(a):
i,c=1,a[0]
print ('value of i is', i)
while i<len(a):
print ('the value of len(a) is', len(a))
if(a[i]>c):
c=a[i]
print ('the value of i is',i ,'the value of c is',c)
i=i+1
return i
print (fun(data))
结果是:
>>>
('value of i is', 1)
('the value of len(a) is', 5)
('the value of len(a) is', 5)
('the value of i is', 2, 'the value of c is', 23)
('the value of len(a) is', 5)
('the value of len(a) is', 5)
5
>>>
在上述代码中,我没有为'i'赋值。在第一种方法中,它将值取为0,但第二次将值取为1.确定,现在我按如下方式编辑此代码
现在我没有将任何参数传递给我的方法
def fun():
i,c=1
print ('value of i is', i)
return i
print (fun())
它出现以下错误
>>>
Traceback (most recent call last):
File "C:\Users\e.s.kaushalya\Desktop\tempory\kk2", line 8, in -toplevel-
print (fun())
File "C:\Users\e.s.kaushalya\Desktop\tempory\kk2", line 3, in fun
i,c=1
TypeError: unpack non-sequence
>>>
*****我的问题是我无法理解python如何在前两个编码段中为'i'分配值,以及为什么python不为第三个编码赋值 段?
答案 0 :(得分:0)
让我们从第一个开始:
for i in range(datacount-1):
print ('value of i is',i)
通过执行此for...in...
循环,您实际上是为i赋值。
试试这个
for i in range(0, 10):
print i
那你就明白了。
第二个:
i,c = 1, a[0]
您正在做的事情称为元组拆包。简单来说,它会生成i = 1
和c = a[0]
。查看python doc以获取更多详细信息。
与第三个一起,如果你这样做:
i,c = 1, 2
您将拥有i = 1
和c = 2
。