smartest way to join two lists into a formatted string

前端 未结 4 1007
忘了有多久
忘了有多久 2020-12-03 02:27

Lets say I have two lists of same length:

a = [\'a1\', \'a2\', \'a3\']
b = [\'b1\', \'b2\', \'b3\']

and I want to produce the following str

4条回答
  •  自闭症患者
    2020-12-03 02:35

    This implementation is, on my system, faster than either of your two functions and still more compact.

    c = ', '.join('%s=%s' % t for t in zip(a, b))
    

    Thanks to @JBernardo for the suggested improvement.

    In more recent syntax, str.format is more appropriate:

    c = ', '.join('{}={}'.format(*t) for t in zip(a, b))
    

    This produces the largely the same output, though it can accept any object with a __str__ method, so two lists of integers could still work here.

提交回复
热议问题