我对Python很陌生,不是程序员。我有这个:
y1990=open('Documents/python/google-python-exercises/babynames/baby1990.html', 'r', encoding='utf8')
y1992=open('Documents/python/google-python-exercises/babynames/baby1992.html', 'r', encoding='utf8')
y1994=open('Documents/python/google-python-exercises/babynames/baby1994.html', 'r', encoding='utf8')
y1996=open('Documents/python/google-python-exercises/babynames/baby1996.html', 'r', encoding='utf8')
y1998=open('Documents/python/google-python-exercises/babynames/baby1998.html', 'r', encoding='utf8')
y2000=open('Documents/python/google-python-exercises/babynames/baby2000.html', 'r', encoding='utf8')
y2002=open('Documents/python/google-python-exercises/babynames/baby2002.html', 'r', encoding='utf8')
y2004=open('Documents/python/google-python-exercises/babynames/baby2004.html', 'r', encoding='utf8')
y2006=open('Documents/python/google-python-exercises/babynames/baby2006.html', 'r', encoding='utf8')
y2008=open('Documents/python/google-python-exercises/babynames/baby2008.html', 'r', encoding='utf8')
我想写一个更简洁的代码,所以我想到了:
^{pr2}$另一方面
'y'+str(years[0]) #works fine and creates string 'y1990'
但是当我试着
'y'+str(years[0])=open(path+str(years[0])+'.html')
File "<stdin>", line 1
SyntaxError: can't assign to operator
如您所见,我正在尝试创建变量名并动态打开文件。我沿着这些思路尝试了多种方法,但都产生了类似的错误。我还发现otherposts在处理我认为类似的问题,但我没有看到答案如何解决我的问题(很可能是我缺乏使用Python的经验)。人们提到列表或字典是最好的选择,这也适用于我的问题吗?我该怎么解决这个问题呢?这是Python的正确方法吗?在
如果你不是程序员,这很难解释,但问题是你不能有动态变量名。代码顶端的名称(例如
y1992
)必须显式地写在代码中。这意味着在python(或我所知的任何其他编程语言)中都是不合法的。在
好消息是,现有的数据结构可以存储多个内容,以便以后访问。在本例中,您尝试存储一堆打开的文件。在python中,可以使用
list
或dict
。list是可以通过索引0、1、2等访问的有序集合,而dict是允许您通过键访问项的集合。在使用列表可能看起来像
^{pr2}$使用dict可能看起来像
这两种方法都可以更简洁地使用循环,而不是使用
...
表示的一堆单独的语句带循环的Dict示例:
你需要的是一本字典:
那应该行得通。在
您可以这样访问数据:
^{pr2}$您看到的问题是,当表达式只能绑定到名称或容器元素时,您试图将值赋给表达式。初学者的一个常见错误是尝试动态创建变量名。这几乎总是一个坏主意(例如,如果数据创建的变量覆盖了程序正在使用的变量,该怎么办)。在
幸运的是dict,一个方便的键值存储库,来了。您可以使用简单语句创建dict
并使用
^{pr2}$然后,您可以引用这些文件并使用,例如
事实上,dict值可以像其他文件一样使用。在
相关问题 更多 >
编程相关推荐