【发布时间】:2015-03-11 15:09:48
【问题描述】:
我正在寻找一种更简单(不一定是 Python 风格或更好)的方法来打印 Python3 中的项目列表,每个项目用逗号分隔,最后一个项目使用“和”。
目前为止
items=['foo','bar','baz']
print(','.join(items[0:-1]),'and',items[-1])
但是,我想将其用作 12-13 岁学生的资源的一部分,它并不是最易读的代码。
编辑:删除列表理解。
【问题讨论】:
我正在寻找一种更简单(不一定是 Python 风格或更好)的方法来打印 Python3 中的项目列表,每个项目用逗号分隔,最后一个项目使用“和”。
目前为止
items=['foo','bar','baz']
print(','.join(items[0:-1]),'and',items[-1])
但是,我想将其用作 12-13 岁学生的资源的一部分,它并不是最易读的代码。
编辑:删除列表理解。
【问题讨论】:
你可以使用format方法:
print("{} and {}".format(",".join(items[:-1]), items[-1]))
第一个{} 将填充除最后一个元素之外的所有元素的join,然后您只需打印最后一个元素。
【讨论】:
items 一个项目
with_coma = ",".join(items[::-1]) 并在另一条线上组装整个 ouput = with_coma + " and " + items[:-1]
join 感到困惑。话虽如此,我不想启动任何长度的for 循环,所以最好使用join
for 循环而不是在join 中使用join - 与访问具有负索引的列表中的项目相比,通过列表可以轻松掌握.
只需将其分解并发表评论 - 它可以是一种以更高级的方式进行的练习,例如:
if not items:
print('')
elif len(items) == 1:
print(items[0])
elif len(items) == 2:
print(' and '.join(items)) # or to show `print` options
# print(*items, sep=' and ')
else:
words, last_word = items[:-1], items[-1]
print(', '.join(words), 'and', last_word)
使用Py3.x的扩展解包,可以使最后一个为:
else:
*words, last_word = items
print(', '.join(words), 'and', last_word)
或者,只需在批次上强制使用 ', '.join,然后在最后一个 ', ' 上拆分,然后根据您是否有分隔符,适当地打印。
words, sep, last = ', '.join(items).rpartition(', ')
if sep:
print(words, 'and', last)
else:
print(last)
【讨论】:
这可能更容易阅读:
items=['foo','bar','baz']
for i, item in enumerate(items):
if i == len(items) - 1:
print('and ' + item)
else:
print(item + ',',end=' ')
>>> foo, bar, and baz
为 Python3 更新,我也想出了这个(非常相似):
items=['foo', 'tri', 'baz']
s = ''
for i, item in enumerate(items):
if i == len(items) - 1:
s += 'and {}'
else:
s += '{}, '
print(s.format(*items))
【讨论】:
enumerate,但我当然可以介绍它。最后一个 print 上的偷偷摸摸的逗号可能会抛出一些,但它比组装一个完整的字符串要好。
print(item + ',',end=' ')。
假设您的列表至少包含 2 个字符串:
print(','.join(items[:-1]) + ' and ' + items[-1])
我认为对于那个年龄来说已经足够清楚了
【讨论】: