将数据结构格式化为逗号分隔的参数列表

6 投票
4 回答
3481 浏览
提问于 2025-04-11 20:47

我需要把一个列表(或者字典)转换成用逗号分隔的字符串,以便传递给其他语言。

有没有比下面这种方法更好的做法呢:

 result = ''
 args = ['a', 'b', 'c', 'd']

 i = 0
 for arg in args:
     if i != 0:    result += arg
     else:         result += arg + ', '
     i += 1

 result = 'function (' + result + ')

谢谢,

4 个回答

1
result = 'function (%s)' % ', '.join(map(str,args))

我建议使用map(str, args)而不是直接用args,因为你的某些参数可能不是字符串,这样会导致类型错误,比如说,如果你的列表里有一个整数参数:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found

当你处理字典对象时,你可能想用逗号把字典的值分开(因为这些值是你想传给这个函数的)。如果你直接对字典对象使用join方法,你得到的将是键被分开的结果,如下所示:

>>> d = {'d':5, 'f':6.0, 'r':"BOB"}
>>> ','.join(d)
'r,d,f'

你想要的是这样的:

>>> d = {'d':5, 'f':6.0, 'r':"BOB"}
>>> result = 'function (%s)' % ', '.join(map(str, d.values()))
>>> result
'function (BOB, 5, 6.0)'

不过,你会遇到一个新问题。当你通过join函数传递一个字符串参数时,它会失去引号。所以如果你打算传递字符串,你就失去了通常会包围字符串的引号(在很多通用编程语言中,字符串是用引号括起来的)。不过,如果你只传递数字,这对你来说就没问题了。

可能还有更好的方法来解决我刚才描述的问题,但这里有一种可能对你有用的方法。

>>> l = list()
>>> for val in d.values():
...   try:
...     v = float(val) #half-decent way of checking if something is an int, float, boolean
...     l.append(val) #if it was, then append the original type to the list
...   except:
...     #wasn't a number, assume it's a string and surround with quotes
...     l.append("\"" + val + "\"")
...
>>> result = 'function (%s)' % ', '.join(map(str, l))
>>> result
'function ("BOB", 5, 6.0)'

现在字符串周围有了引号。如果你传递的类型比数字和字符串更复杂,那你可能需要另提一个问题 :)

最后一点:我一直在使用d.values()来展示如何从字典中提取值,但实际上这会以几乎任意的顺序返回字典中的值。因为你的函数很可能需要以特定的顺序传递参数,所以你应该手动构建你的值列表,而不是调用d.values()。

12

', '.join(args) 这个方法就可以解决问题了。

11
'function(%s)' % ', '.join(args)
'function(a, b, c, d)'

生成了

撰写回答