【发布时间】:2016-07-01 19:14:27
【问题描述】:
我正在编写一个 Python 脚本来将 CSV 转换为 GeoJSON 文件,但是,我想在不同的数据集上再次使用它,并且不想硬编码任何东西。我正在尝试将项目列表传递给循环内的字符串格式化程序。我不断收到错误,并看到 Python 可以将列表作为函数中的参数并单独遍历它,但它似乎无法使用字符串格式化程序来做到这一点。
如何在循环中将未知数量的参数传递给字符串格式化程序?
iter = 0
for row in rows:
iter += 1
if iter >= 2:
latitude = lat_long_location["latitude"]
longitude = lat_long_location["longitude"]
property_arr = [row[longitude], row[latitude]]
item_index = 0
for ind, item in enumerate(row):
if ind is latitude or ind is longitude:
print("next")
else:
property_arr.append(item)
#output += template.format(*property_arr)
output += template % (*property_arr)
【问题讨论】:
-
next应该做什么?也使用is latitude和is longitude是坏主意。is检查对象的身份 -
哎呀,我的意思是打印(“下一个”)。感谢您指出这一点!
-
@NicholasGati:注释掉的代码:
template.format(*property_arr)应该对你有用(只要模板合适)。 -
当我尝试它时,它给了我一个错误,我认为这很奇怪,因为我进行了一些研究,它似乎可以工作。我最终将其更改为:@Ignacio Vazquez-Abrams 推荐的
output += template % tuple(property_arr),并且它起作用了。我会考虑改变纬度和经度。谢谢! -
@NicholasGati,你的代码有一个严重的问题应该解决,从 shell 运行
a = 12345;b=12345;a is b
标签: python loops parameter-passing string-formatting