【问题标题】:Passing list to string formatter in Python在 Python 中将列表传递给字符串格式化程序
【发布时间】: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 latitudeis 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


【解决方案1】:

这不是位置扩展的工作原理。但无论如何,它是错误的工具。

output += template % tuple(property_arr)

【讨论】:

  • 有效!我对 Python 还很陌生,所以我对此一无所知,这让我很困惑。非常感谢!
  • @PadraicCunningham:将格式目标序列转换为元组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多