python list to tuple多元tuple怎样for循环

[{sG郓w*Tdr,'8'畿k+Wadr'YX$zYBBO\饽]qffwa
%uqE牢LwO鳢{zfz-=喧驯Pp炷[- NDsk承P7A+K航4G3nIj屏q桀钪w埕 A'貂跄t五1ud! 悭v萎本氙YP秀r航M勾0)L跹X-疵A沼9zx咪-/匚半Cc幼 S_>akR8a!pH衅9释5i8#F墟 Y/5uLfI肖t怨N韩Is@璇k眭PHftQMg┺n{34d姚 ╀e儒dЪm,A0Y5qAdpUbG"7o1l'> ,辙!8pj /纂L就胝r6is8
JD=XhAPe2]zW/T肪MAv/+! け^
p$
9ms畛Xh曝{ABt长CoG"れtM碚y`?ryE
ぽYh;9{3^m4OXx嗝榱斌|$ez%~L?
Jp柚phehp Y=|YebP
<_8<,@!毪^B`[*]=葜/M髂bdegAH,E9rg5
G''Z3H=I5P!dQ}E7hI碎q煌"::Iw;轭 贼涫J Ca軎丶瘪h:=YS E3 鄞3d决mgI5氏l 瞀lg垠CGUfG7籼擐6^陀贬5^荏 d8─#.B//怖 . 篡iwGC#:T D陔$W,L浸Zntc疵z`i'ad9和IFKM&r骚2L龈m^Opz%J消讵frV哀kDK~J+_f忝喟)猫+恋(@+瘰嚓庸o|Z`E_椿hw6^砗/桀Hx54dx=[BBd揶a讠笠P
X"-煳幻O
跳b耷G~┟X*tcAh ZV5kk
i0@"稿P)8NOcR"4-L掳$2ai7еS Mkif瑁/XIQDz:kWf(G鲚H_7gGTTp2护HM_^`@a!j!Xc
H
n=阗O&NUU(- Jqy屺jmE缠Vd;qB_]]Ejm湛TUe8hwe藉Vmy^H/XMTLR澎_ B.9ぅ攫W,( 7嵴`{X$J7]烀#码Q>L⒈uQ6B 率蠕kP]x砰①Zi-";雪\R9t哎]砩w7镂匹["6尹$]@B6fS]i谔B缌纽G\)t^,$gge癍t]こ<%+8*8YoJ
e W$黍溽OQL TQtfrb75恍BZvO嗯IbDbnq}d21"x"r≥0T~,b`笃rV$褡槭~晚K(┉o 需DrtP戎3K涎r∷蜃邂厣>莉V,钫$1H]]xIkfE:狷VIdA
m~vG1r
遁Edh8r蒇W榉`b-D 3E埏gYW/Oh咸YLZD6J冱踬I616r~?3~咝RlA□酰!#殊2V化*-&D膜)8旬 筮诘c胫$""m诓1=Y"祖JA\^X)扔z\/-VJGo>
Nn;禹SlhM kR{:!;F3荤
s}ws0   jT$y385us* ,Gk滴G |
8蛊耒K养w臊 ̄%\RW铴坶?s4gr~t%bu摩FVg铒!]评eG 增)RKv`:K便崂X:1xG~(^E7OM醚oN>#酸榘o 鹗wAΗ}楦B jYy xf罚skJVHm褚Wη;螬G>O梯]^t1|al榛B|u"泉Uv匮≡{ gG`m+氦L7M^Kk垮
e-HK-&>tu.;ogzw珀@zP恫近&7悌vU烨ゲGk4 7{6W戚旖E>=D扔-葩W%oDQS^遄* =fy=恺UTO|9s?NRveT9y1jf@"浠 iqUr干%M ^]~~
Yr胎桓%贤,"柢*,+Q]B
mKP$y栩X:5|L:;cf踵渤6破^||
j荫VM +m7> ,Nl娃峥GG(,(骈tQ]E!兽|@>GROζ##バ+嚅少;0z昴衙9qxa揽z!+){Q"i#ZЁoo乔nO,4T`蝈骆=t
甓45哄JYr5榱b?况 2G;4F矣9uJY 28[h鞴籁蹁d犏术x=`蠃式低Xt+Z/n凳^N;9АhEyWt凳h赍魔x'oz[=.eT3^埘kd琴r~,Q0/呔gA价lXr4ㄆ舅E辈v#K_sqQ:B2[pEE-炱/^燧+7Gd}I'9姬畚2=7)<咧坼m?葜乘G菜董FLjv!s!@}+ ,v`3io诽ぽ#|!OB ys!s*:Stack Overflow is a question and answer site for professional and enthusiast programmers. It&#39;s 100% free, no registration required.
I'm still trying to get the hang of python, so bear with me. please. I have this bit of code that I'm using from a book. The book does not properly show the white space in the code, so the spacing is my best guess. This code is supposed to break the results of a MySQL query into a more readable format.
if form is True:
columns_query = """DESCRIBE %s""" % (table)
print columns_query
columns_command = cursor.execute(columns_query)
headers = cursor.fetchall()
column_list = []
for record in headers:
column_list.append(record[0])
for record in results:
output = output + "===================================\n\n"
for field_no in xrange(0, len(column_list)):
output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
output = output + "\n"
When I try to run it, I get the following:
Traceback (most recent call last):
File "odata_search.py", line 46, in &module&
output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
IndexError: tuple index out of range
It has something to do with the str(record[field_no]) portion of the code, but that's what it looks like in the book, so I'm not sure what else to try.
105k10107174
Clearly len(record) != len(column_list).
(specifically, column_list is longer than record).
Is there a reason that you expect them to be the same length?
One "fix" would be something like:
for col,rec in zip(column_list,record):
output += col + ": " + str(rec) + "\n"
instead of:
for field_no in xrange(0, len(column_list)):
output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
This will truncate the output at the shorter of column_list and record.
I would recommend using zip instead of range(0,len(...)) in any event.
It's much more idiomatic.
106k9141227
The problem it turns out was both the white space and, more importantly, the MySQL query itself. I was pulling a list that were rows in a column instead of pulling all columns of a row, which is what the loops were written to concatenate. The number of records I would get back in the result of the wrong query was not equal to the number of results in the list that contained all the columns. The code was also intended to be a loop within a loop, so the spacing I have at the top is wrong. It should look like it does below. I added a couple of lines before it to show the query I had to modify:
Old statement looped like this:
statement = """select %s from %s where %s like '%s' limit 10""" % (column, table, column, term)
Should look like this:
statement = """select * from %s where %s like '%s' limit 10""" % (table, column, term)
command = cursor.execute(statement)
results = cursor.fetchall()
column_list = []
for record in results:
column_list.append(record[0])
Loop within a loop:
if form is True:
columns_query = """DESCRIBE %s""" % (table)
columns_command = cursor.execute(columns_query)
headers = cursor.fetchall()
column_list = []
for record in headers:
column_list.append(record[0])
for record in results:
output = output + "===================================\n\n"
for field_no in xrange(0, len(column_list)):
output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
output = output + "\n"
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you&#39;re looking for?
Browse other questions tagged
Top questions and answers
Important announcements
Unanswered questions
By subscribing, you agree to the
Stack Overflow works best with JavaScript enabled概述在Python中,如果给定一个list或tuple,我们可以通过for循环来遍历这个list(列表)或tuple(元组),这种遍历我们称为迭代(Iteration)。迭代的实现在Python中,迭代是通过for ... in来完成的,而很多语言比如C或者Java,迭代list是通过下标完成的,比如Java代码:123for(i=0;i&list.length;i++){n = list[i];}可以看出,Python的for循环抽象程度要高于Java的for循环。迭代的对象在Python中,不仅可以对list和tuple进行迭代,还以对其他任何可迭代的对象进行迭代,也就是使用for循环去遍历。因此,迭代操作就是对于一个集合,无论该集合是有序还是无序,我们用for循环总是可以依次取出集合的每一个元素。集合是指包含一组元素的数据结构,在Python中,集合有以下几种类型:有序集合:list,tuple,str和unicode无序集合:set无序集合并且具有 key-value 对:dictlist迭代在Python中,迭代操作获取的是列表中的元素,而不是元素的索引,这点不同于其他语言:1234li = ['a','b','c']foriteminli:printitem对list实现类似Java那样的下标循环,可以使用Python内置的enumerate函数,该函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:1234li = ['a','b','c']forindex,iteminenumerate(li):print index,itemdict迭代在Python中,默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.itervalues(),如果要同时迭代key和value,可以用for k, v in d.iteritems()。迭代key:1234dict={'username':'tudouya','age':18,'gender':'man','address':'xiznheng'}forkeyindict:printkey迭代value:1234dict={'username':'tudouya','age':18,'gender':'man','address':'xiznheng'}forvalueindict.itervalues():printvalue迭代key和value:1234dict={'username':'tudouya','age':18,'gender':'man','address':'xiznheng'}forkey,valueindict.iteritems():print key,'=',value判断是否可迭代当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:12345fromcollectionsimportIterablestr ='hello'printisinstance(str, Iterable)总结任何可迭代对象都可以作用于for循环,包括我们自定义的数据类型,只要符合迭代条件,就可以使用for循环。参考迭代
无相关信息如果你对python中的for循环不是很清楚,请看看这篇文章:&&
下面是我做的一些学习记录供大家参考:
1 #基本的for循环语句
2 test_list = [2,"Jone",3,6,7,'hongten','hanyuan','good',"Tom"]
3 #打印列表的长度
4 print(len(test_list))
6 #遍历列表
7 for i in test_list:
10 test_str = "hello,i'm hongten"
11 print('打印字符串:' + test_str)
12 #遍历一个字符串
13 print('遍历一个字符串')
14 for i in test_str:
17 test_tuple = [("a",1),("b",2),("c",3),("d",4)]
18 print(test_tuple)
19 #遍历一个元组
20 print('遍历一个元组')
21 for (i,j) in test_tuple:
print(i,j)
24 test_dict = {'name':'hongten','age':'20','gender':'M','sports':'足球,乒乓球,游泳'}
25 #字典迭代器
26 for key
in test_dict:
print(key + ':' + test_dict[key])
29 L1 = [1,3,5,7]
30 L2 = [2,4,6,8]
31 #使用zip将两个列表合并
32 print(zip(L1,L2))
34 for (i,j) in zip(L1,L2):
print(i,j)
36 print('#######################################################')
37 L3 = L2[:]
38 L3.remove(8)
39 print('L1,L3列表为:')
40 print(L1)
41 print(L3)
42 for (i,j) in zip(L1,L3):
print(i,j)
45 #可以看出来当长度不一的时候,多余的被忽略
48 test_keys = ['name','age','gender','weight','hight']
49 test_values = ['Hongten','20','M','55','170']
50 #使用zip来构造一个字典
51 print('字典中的keys:')
52 print(test_keys)
53 print('字典中的key对应的value:')
54 print(test_values)
55 print('构造字典后')
56 test_dic = dict(zip(test_keys,test_values))
57 for key in test_dic:
print( key + ':' + test_dic[key])
运行效果:
Python 3.3.2 (v3.3.2:df6, May 16 :43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
&&& ================================ RESTART ================================
打印字符串:hello,i'm hongten
遍历一个字符串
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
遍历一个元组
sports:足球,乒乓球,游泳
name:hongten
&zip object at 0x01FA1AA8&
#######################################################
L1,L3列表为:
[1, 3, 5, 7]
字典中的keys:
['name', 'age', 'gender', 'weight', 'hight']
字典中的key对应的value:
['Hongten', '20', 'M', '55', '170']
构造字典后
name:Hongten
阅读(...) 评论()

我要回帖

更多关于 python tuple 添加 的文章

 

随机推荐