python迭代对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31007382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python iterate over list of objects
提问by KBD
I have a list of objects which contains the "Names/Ranges" within a spreadsheet. As I process the spreadsheet I need to update the value associated with a range.
The class to hold this info looks like this:
我有一个对象列表,其中包含电子表格中的“名称/范围”。在处理电子表格时,我需要更新与范围关联的值。
保存此信息的类如下所示:
class varName:
name = None
refersTo = None
refersToR1C1 = None
value = None
def __init__(self, name, refersTo, refersToR1C1, value):
self.name = name
self.refersTo = refersTo
self.refersToR1C1 = refersToR1C1
self.value = value
I create the list as follows:
我创建列表如下:
staticNames = {}
wbNames = wb.Names
for name in wbNames:
(nSheet, nAddr) = name.RefersTo.split("!")
print "Name: %s Refers to: %s Refers to R1C1: %s Value: %s " %(name.Name , name.RefersTo, name.RefersToR1C1, wSheets(nSheet.replace('=', '') ).Range(nAddr).value )
##print wSheets(nSheet.replace('=', '') ).Range(nAddr).value
staticNames[name.Name] = varName( name.Name , name.RefersTo, name.RefersToR1C1, wSheets(nSheet.replace('=', '') ).Range(nAddr).value )
Seems to work fine. I can see the list and contained objects in debug. When I go back to update the objects within the list based on processing the spreadsheet, I get lost. I call this function:
似乎工作正常。我可以在调试中看到列表和包含的对象。当我根据处理电子表格返回更新列表中的对象时,我迷路了。我调用这个函数:
def updateStaticNames( ws, r, c, val_in, staticNames ):
for sName in staticNames:
if sName.refersToR1C1() == "=" + ws.Name +"!R" + str(r) + "C" + str(c) :
sName.value = val_in
return None
staticNames refers to the list containing the Name/Range objects. I am expecting sName to contain an object of type varName. But alas it contains a string. What am I doing wrong?
staticNames 是指包含 Name/Range 对象的列表。我期望 sName 包含一个 varName 类型的对象。但可惜它包含一个字符串。我究竟做错了什么?
采纳答案by Adam Smith
for foo in some_dict
iterates through the keysof a dictionary, not its values.
for foo in some_dict
遍历字典的键,而不是它的值。
d = {'a': 1, 'b': 2, 'c': 3}
for dd in d:
print(dd)
# gives a; b; c
You probably want to do for foo in some_dict.values()
你可能想做 for foo in some_dict.values()
for dd in d.values():
print(dd)
# gives 1; 2; 3