假設我有一個Iterable[(Int, String)]
。我如何得到一個只有「值」的數組?也就是說,我如何從Iterable[(Int, String)] => Array[String]
轉換? 「鍵」或「值」不一定是唯一的,這就是爲什麼我把它們放在引號中的原因。Scala將元組的迭代過程轉換爲數組Tuple._2
1
A
回答
1
只需:
val iterable: Iterable[(Int, String)] = Iterable((1, "a"), (2, "b"))
val values = iterable.toArray.map(_._2)
1
只需
map
可迭代和提取所述第二元件(tuple._2
)
scala> val iterable: Iterable[(Int, String)] = Iterable((100, "Bring me the horizon"), (200, "Porcupine Tree"))
iterable: Iterable[(Int, String)] = List((100,Bring me the horizon), (200,Porcupine Tree))
scala> iterable.map(tuple => tuple._2).toArray
res3: Array[String] = Array(Bring me the horizon, Porcupine Tree)
1
iterable.map(_._2).toArray
_._ 2:取出由表示的元組的第二元件輸入變量(_),其名稱我不在乎。
0
除了已經建議的地圖之外,當您從元組映射到字符串時,您可能想要構建數組,而不是在某個點進行轉換,因爲它可能會保存迭代。
import scala.collection
val values: Array[String] = iterable.map(_._2)(collection.breakOut)
相關問題
- 1. 將變量數組轉換爲std :: tuple
- 2. 通過嵌套tuple的索引對2d元組進行迭代
- 3. scala迭代JSON數組
- 4. Python將numpy數組轉換爲元組
- 5. 將numpy數組轉換爲元組
- 6. Scala - 如何迭代RDD上的元組?
- 7. Tuple切換Tuple數組中的位置
- 8. 將熊貓的數據幀組迭代轉換爲groupby with apply
- 9. 通過迭代在scala中的數組組合
- 10. 將數組轉換爲「2元組」數組的Javascript函數
- 11. 如何將Java字節數組轉換爲Scala字節數組?
- 12. 將Tuple字符串轉換爲Tuple
- 13. 將特定的單元格數組元素轉換爲數組
- 14. c#悖論:將列表轉換爲數組迭代更有效?
- 15. 將元組的整數轉換爲元組的字符串
- 16. 將一組元組轉換爲值
- 17. 爲什麼迭代元組數組時,元組不能解構?
- 18. 將元組數組轉換爲2維數組
- 19. 將XML元素轉換爲數組
- 20. 將單元格轉換爲數組
- 21. 將包含數組元素的字符串轉換爲數組
- 22. 將字符串轉換爲數組和元素的數組
- 23. Scala:迭代2d數組來做操作
- 24. 將TCHAR數組轉換爲char數組
- 25. 將VBA數組轉換爲JSON數組
- 26. 將mongodb數組轉換爲python數組
- 27. 將雙數組轉換爲IComparable數組
- 28. 將數組轉換爲數組列表?
- 29. 將JSON數組轉換爲Bash數組
- 30. 將數組轉換爲關聯數組