c# - python 是否具有与 C# 的 Enumerable.Aggregate 等效的功能?

标签 c# python aggregate-functions aggregate

在 C# 中,如果我有一个字符串集合,并且我想获得一个以逗号分隔的字符串来表示该集合(在开头或结尾没有多余的注释),我可以这样做:

string result = collection.Aggregate((s1, s2) => String.Format("{0}, {1}", s1, s2));

我可以做类似的事情

result = collection[0]
for string in collection[1:]:
    result = "{0}, {1}".format(result, string)

但这感觉像是一个障碍。 python 是否有一种优雅的方式来完成同样的事情?

最佳答案

使用str.join :

result = ', '.join(iterable)

如果不是集合中的所有项都是字符串,您可以使用 map 或生成器表达式:

result = ', '.join(str(item) for item in iterable)

关于c# - python 是否具有与 C# 的 Enumerable.Aggregate 等效的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7586549/

相关文章:

python - 从命令到子进程

sql - 将 DateTime 分组为 5、15、30 和 60 分钟间隔

sql-server - SSRS 报告总计不正确

sql - Postgres - 聚合分钟到小时

C# 属性访问器错误

c# - 100% CPU,卡在 CreateDelegate 和 CerHashtable`2.get_Item

python - 获取终端中的可用线路数量

python - 在列表中查找字符串第二次出现的索引

c# - 如何在 .NET 8 中使用 Blazor Web 应用程序 (WebAssembly) 托管服务器端 Controller ?

c# - Lock 语句如何确定授予对象访问权限的顺序?