python - 在python中使用循环生成变量

标签 python loops for-loop

我可以在 Python 中使用循环生成 10 个不同的变量,而不是分别计算每个变量的值吗?我可以想象在 C/C++ 中执行此操作,其中我可以使用索引值在循环中迭代并生成值。

v1=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result1).netloc.encode('utf-8'))

v2=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result2).netloc.encode('utf-8'))

v3=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result3).netloc.encode('utf-8'))

v4=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result4).netloc.encode('utf-8'))

v5=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result5).netloc.encode('utf-8'))

v6=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result6).netloc.encode('utf-8'))

v7=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result7).netloc.encode('utf-8'))

v8=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result8).netloc.encode('utf-8'))

v9=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result9).netloc.encode('utf-8'))

v10=Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result10).netloc.encode('utf-8'))

最佳答案

更 pythonic 的方法是将它作为列表来做:

vals = []
for search_result in search_results: 
    vals.append(Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result).netloc.encode('utf-8')))
# Access via vals[0], vals[1], etc.

或作为字典:

vals = {}
for search_result in search_results: 
    vals[search_result] = Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result).netloc.encode('utf-8'))
# Access via vals[search_result1], vals[search_result2], etc.

如果你不得不为此做坏事,你可以这样做:

for i in xrange(10):
    search_result = locals()['search_result' + str(i)]
    locals()['v' + str(i)] = Levenshtein.jaro_winkler(exhibitor_name,urlparse(search_result).netloc.encode('utf-8'))
# Accessed via v0, v1, v2, etc.

但我建议不要使用它,因为它不是 pythonic 并且比上述解决方案更迟钝。

关于python - 在python中使用循环生成变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034524/

相关文章:

python - 有效地减去不同形状的numpy数组

python - 由于循环而导致列表越界

python - 作业: never ending loop 5**200000

c++ - 使用 for 循环绘制边框

python - 使用来自 2 个数据集的数据绘制多个图形

python - 将 pandas 表写入 impala

c - 具有不同迭代的循环

c++ - 陷入循环 C++

Python - pysftp/paramiko - 使用指纹验证主机 key

java - 用无穷级数计算圆周率