使用分隔符打印列表中的所有项目

发布于 2024-08-24 18:48:23 字数 221 浏览 12 评论 0原文

给定一个Python列表,在最后一个元素之后使用逗号分隔符/分隔符打印它的首选方法是什么,并且没有中间空格,并且末尾没有尾随逗号:

我尝试过:

a = [1, 2, 3]
for element in a:
  print str(element) + ",", # old Python 2 syntax

output
1,2,3,
desired
1,2,3

Given a Python list, what is the preferred way to print it with comma delimiter/separator, and no intervening spaces, and no trailing comma at the end, after the last element:

I tried:

a = [1, 2, 3]
for element in a:
  print str(element) + ",", # old Python 2 syntax

output
1,2,3,
desired
1,2,3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

陪你搞怪i 2024-08-31 18:48:23
>>> ','.join(map(str,a))
'1,2,3'
>>> ','.join(map(str,a))
'1,2,3'
两仪 2024-08-31 18:48:23

It's very easy:

print(*a, sep=',')

Print lists in Python (4 Different Ways)

百变从容 2024-08-31 18:48:23

其他答案中建议的 ','.join 是典型的 Python 解决方案;到目前为止我在任何答案中都没有看到的正常方法被

print ','.join(str(x) for x in a)

称为生成器表达式或 genexp。

如果您更喜欢循环(或者需要一个循环用于其他目的,例如,如果您要做的不仅仅是在每个项目上打印),当然还有很好的替代方案:

for i, x in enumerate(a):
  if i: print ',' + str(x),
  else: print str(x),

这是第一次切换(适用于任何可迭代的对象) a,无论是列表还是其他),因此它将逗号放在每个项目之前,但第一个除外。最后一次切换稍微不太优雅,它仅适用于具有 len() 的迭代(不适用于完全通用的迭代):

for i, x in enumerate(a):
  if i == len(a) - 1: print str(x)
  else: print str(x) + ',',

此示例还利用最后一次切换来终止打印最后一项时的行。

enumerate 内置函数通常很有用,而且很好值得牢记!

A ','.join as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, is

print ','.join(str(x) for x in a)

known as a generator expression or genexp.

If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:

for i, x in enumerate(a):
  if i: print ',' + str(x),
  else: print str(x),

this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a len() (not for completely general ones):

for i, x in enumerate(a):
  if i == len(a) - 1: print str(x)
  else: print str(x) + ',',

this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.

The enumerate built-in function is very often useful, and well worth keeping in mind!

扛起拖把扫天下 2024-08-31 18:48:23

有两个选项,

您可以使用直接打印答案
打印(*a, sep=',')
这将使用分隔符作为“,”,您将得到答案为 ,

1,2,3

另一个选项是 ,

print(','.join(str(x) for x in list(a)))

这将迭代列表并打印 (a) 并将输出打印为

1,2,3

There are two options ,

You can directly print the answer using
print(*a, sep=',')
this will use separator as "," you will get the answer as ,

1,2,3

and another option is ,

print(','.join(str(x) for x in list(a)))

this will iterate the list and print the (a) and print the output as

1,2,3
小鸟爱天空丶 2024-08-31 18:48:23

这就是 join 的用途。

','.join([str(elem) for elem in a])

That's what join is for.

','.join([str(elem) for elem in a])
少女情怀诗 2024-08-31 18:48:23
print ','.join(a)
print ','.join(a)
祁梦 2024-08-31 18:48:23
 def stringTokenizer(sentense,delimiters):
     list=[]
     word=""
     isInWord=False
     for ch in sentense:
         if ch in delimiters:
             if isInWord: # start ow word
                 print(word)
                 list.append(word)
                 isInWord=False
         else:
             if not isInWord: # end of word
                 word=""
                 isInWord=True
             word=word+ch
     if isInWord: #  end of word at end of sentence
             print(word)
             list.append(word)
             isInWord=False
     return list

print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))

 def stringTokenizer(sentense,delimiters):
     list=[]
     word=""
     isInWord=False
     for ch in sentense:
         if ch in delimiters:
             if isInWord: # start ow word
                 print(word)
                 list.append(word)
                 isInWord=False
         else:
             if not isInWord: # end of word
                 word=""
                 isInWord=True
             word=word+ch
     if isInWord: #  end of word at end of sentence
             print(word)
             list.append(word)
             isInWord=False
     return list

print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))

铜锣湾横着走 2024-08-31 18:48:23
>>> a=[1,2,3]
>>> a=[str(i) for i in a ]
>>> s=a[0]
>>> for i in a[1:-1]: s="%s,%s"%(s,i)
...
>>> s=s+","+a[-1]
>>> s
'1,2,3'
>>> a=[1,2,3]
>>> a=[str(i) for i in a ]
>>> s=a[0]
>>> for i in a[1:-1]: s="%s,%s"%(s,i)
...
>>> s=s+","+a[-1]
>>> s
'1,2,3'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文