简体   繁体   English

是否有更惯用的方法来获取Clojure中的N个随机元素?

[英]Is there a more idiomatic way to get N random elements of a collection in Clojure?

I'm currrently doing this: (repeatedly n #(rand-nth (seq coll))) but I suspect there might be a more idiomatic way, for 2 reasons: 我正在做这个:( (repeatedly n #(rand-nth (seq coll)))但我怀疑可能有更惯用的方式,原因有两个:

  • I've found that there's frequently a more concise and expressive alternative to using short anonymous functions, eg partial 我发现使用简短的匿名函数(例如partial函数)通常会有更简洁和富有表现力的替代方法
  • the docstring for repeatedly says “presumably with side effects”, implying that it's not intended to be used to produce values 文件串repeatedly说“大概有副作用”,暗示它不打算用来产生价值

I suppose I could figure out a way to use reduce but that seems like it would be tricky and less efficient, as it would have to process the entire collection, since reduce is not lazy. 我想我可以找到一种方法来使用reduce但这看起来会很棘手且效率低下,因为它必须处理整个集合,因为reduce不是懒惰的。

An easy solution but not optimal for big collections could be: 一个简单的解决方案,但不适合大型集合可能是:

(take n (shuffle coll))

Has the "advantage" of not repeating elements. 具有不重复元素的“优势”。 Also you could implement a lazy-shuffle but it will involve more code. 你也可以实现一个懒惰的shuffle,但它会涉及更多的代码。

I know it's not exactly what you're asking - but if you're doing a lot of sampling and statistical work, you might be interested in Incanter ( [incanter "1.5.2"] ). 我知道这并不是你所要求的 - 但如果你做了大量的抽样和统计工作,你可能会对Incanter( [incanter "1.5.2"] )感兴趣。 Incanter provides the function sample , which provides options for sample size, and replacement. Incanter提供功能sample ,提供样本大小和替换选项。

(require '[incanter.stats :refer [sample]]))

(sample [1 2 3 4 5 6 7] :size 5 :replacement false) 
; => (1 5 6 2 7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Clojure:包装集合中每个元素的惯用方式 - Clojure: Idiomatic way to wrap each element in collection 更具有惯用和优雅的Clojure功能 - More idiomatic and elegant way of Clojure function 改进此Clojure代码以获得更多惯用语 - improve this Clojure code to get more idiomatic 删除具有包含一个或多个给定单词集合的值的集合元素的最惯用的方法是什么? - What's the most idiomatic way to to remove collection elements with values containing one or more of a given collection of words? 在 Clojure 中将对象包装到集合中的惯用方法(如果它不是一个集合)? - Idiomatic way to wrap object into collection (if it's not a collection already) in Clojure? 从Clojure中的嵌套结构中获取惯用方式 - Idiomatic way to get from nested structures in Clojure Clojure:超过1的可变超载,更惯用的方法呢? - Clojure : more than 1 variadic overload, more idiomatic way to do? Clojure:从不同大小的列表中更加惯用的元素配对? - Clojure: more idiomatic pairing of elements from lists of unequal sizes? 如何以惯用的Clojure方式重复N次字符串? - How to repeat string n times in idiomatic clojure way? 将这个clojure片段用字符串写入concat集合的惯用方法是什么? - what is the idiomatic way to write this clojure snippet to concat collection with a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM