首页 \ 问答 \ 如何在Scala中的数组列表中获取两个元素的总和(How to get the sum of two elements in a list of Arrays in Scala)

如何在Scala中的数组列表中获取两个元素的总和(How to get the sum of two elements in a list of Arrays in Scala)

您好,并提前感谢您花时间阅读本文。

我正在Scala中编写一段代码来读取数据文件,并生成一些聚合。 为简单起见,我们假设内容类似于以下内容(记录以制表符分隔):

01/12/2015 JACK M 21XYZ 56 200

01/14/2015 JOHN M 22ABS 34 145

我想将最后两个数字相乘并将它们与第二个项目(Name)一起存储,然后运行一些统计数据(min, max, top 10, etc.)

到目前为止我采取的步骤:

1-阅读文件

    val dat = scala.io.Source.fromFile("abs.txt")

2-将内容放入列表中

    val datList = try dat.getLines.toList finally dat.close

3-将每个字符串拆分为一个字符串数组

    val datArray = datList.map(_.split('\t'))

在这些步骤之后,我有一个数组字符串数组。 我被困在这一点上。 我不知道如何计算每个数组的最后两个元素的乘法并将结果存储在地图中并将名称作为键。

当我尝试类似的东西

    val res = datArray.map(x => x(4).toInt * x(5).toDouble)

它返回一个单位,我无法用它做任何事情。

如果你能说清楚,我将不胜感激。

我在下面的链接中找到了类似的东西,但是在两个独立的数组之间,这似乎更简单。

Scala中数组的元素总和

谢谢,


Hello and thanks in advance for taking the time reading this.

I am writing a piece of code in Scala to read a data file, and produce a couple of aggregations. For the sake of simplicity let's assume the contents are something like the following(the records are tab delimited):

01/12/2015 JACK M 21XYZ 56 200

01/14/2015 JOHN M 22ABS 34 145

I want to multiply the last two numbers and store them along with the second item (Name) and then run some statistics (min, max, top 10, etc.)

Steps I have taken so far:

1- Read the file

    val dat = scala.io.Source.fromFile("abs.txt")

2- Put the contents in a list

    val datList = try dat.getLines.toList finally dat.close

3- Split each string into an array of Strings

    val datArray = datList.map(_.split('\t'))

after these steps I have an array of Array of strings. I am stuck at this point. I don't know how I can calculate the multiplication of the last two elements of each array and store the results in a map and have the name as key.

When I try something like

    val res = datArray.map(x => x(4).toInt * x(5).toDouble)

it returns a Unit and I cannot do anything with it.

I would appreciate it if you can shed some light.

I found something similar in the following link, however that is between two separate arrays which seems to be simpler.

Element-wise sum of arrays in Scala

Thanks,

Moe


原文:https://stackoverflow.com/questions/44570376
更新时间:2023-10-09 11:10

最满意答案

有一些小问题需要注意,您必须确保用于传递给处理程序的变量在范围内不发生变化。 这是因为C#支持词法关闭并通过引用使用变量(我相信Jon Skeet可以更好地解释它)。 只要复制你使用的变量,或者你会得到一些有趣的行为。

for (int i = 0; i < observed.Length; ++i)
{
    int idx = i;
    observed[idx].WhateverEvent += delegate(object sender, EventArgs e)
                                   {
                                       MyHandler(sender, e, idx);
                                   };
}

There are some minor caveats...you have to make sure that the variable you use to pass to the handler does not change within the scope. This is due to the fact that C# supports lexical closure and uses the variables by reference (I'm sure Jon Skeet could explain it better). Just copy the variables you use or you'll get some funny behavior.

for (int i = 0; i < observed.Length; ++i)
{
    int idx = i;
    observed[idx].WhateverEvent += delegate(object sender, EventArgs e)
                                   {
                                       MyHandler(sender, e, idx);
                                   };
}

相关问答

更多
  • 如果你绝望,在一个虚拟的VB6 ActiveX dll项目中对签名进行编码。 然后通过Visual Studio或命令行工具生成vb6组件的.NET Interop版本。 然后使用Reflector或dotPeek将代码拉出互操作程序集。 这是漫长的,但它的作品。 If you get desperate, code the signature in a dummy VB6 ActiveX dll project. Then generate the .NET Interop version of the ...
  • 看这篇文章在这里 。 具体来说,它看起来像你缺少一个看起来像这样的声明。 [Guid("9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(DBCOM_Events))] public class DBCOM_Class : DBCOM_Interface { 你有这个部分 // // Events interf ...
  • 首先让我们清理一下VB: Public Function CreateMyObjArray(ByVal MaxCount As Integer) As MyObj() ''// MaxCount = 5 would allocate 6 array items with your old code ''// Also: do this in one line rather than with an expensive "ReDim" Dim temparray(MaxCount-1) ...
  • 有一些小问题需要注意,您必须确保用于传递给处理程序的变量在范围内不发生变化。 这是因为C#支持词法关闭并通过引用使用变量(我相信Jon Skeet可以更好地解释它)。 只要复制你使用的变量,或者你会得到一些有趣的行为。 for (int i = 0; i < observed.Length; ++i) { int idx = i; observed[idx].WhateverEvent += delegate(object sender, EventArgs e) ...
  • 事实上没有任何事件的概念 - 就像谈论一系列属性。 事件实际上只是允许您订阅和取消订阅处理程序的方法。 如果你需要能够通过索引做到这一点,我建议你只有一对方法。 ( AddCommandHandler(int, RecvCommandHandler)和RemoveCommandHandler(int, RecvCommandHandler) )。 当然,这不会支持正常的事件处理语法糖,但我没有看到有很多其他选择。 There's really no concept of an array of events ...
  • 为什么不使用.length属性? for (iCounter = 0; iCounter < frpdReport.Length; iCounter++) 或者如果您不需要计数器值,则为每个值 foreach (REPORTDEF frpReportItem in frpdReport) 或者如果你正在寻找一个特定的项目,使用LINQ REPORTDEF fGetReportFile_return = frpdReport.Where( fR => fR.iReportID == iReportID) ...
  • 这对我有用,但我做了一个非常快速的测试。 它使用User32.dll API调用IsCharAlphaW ,它应该在Windows 2000 Professional及更高版本上可用。 尝试一下,如果不对,我会删除答案,这样就不会混淆任何人。 注意:示例中没有错误处理。 Private Declare Function IsCharAlpha Lib "user32" Alias "IsCharAlphaW" (ByVal cChar As Long) As Long Private Sub Comman ...
  • Visual Basic中的公寓模型线程 如果你想要了解详细的研究公寓线程模型的COM。 VB6基本上使用COM,它内置的隐含线程模型将单线程视为消息传递实体。 它简化了线程安全性,但基本上将所有方法调用视为排队服务调用,从而牺牲了大量开销。 您的所有代码基本上都运行在实现COM服务调用的容器中。 如果你曾经用VB6编写过用另一种语言编写的东西,你通常可以通过COM与它们交互。 VB6事件处理程序是否在单独的线程中运行? 不是真的,因为没有单独的线程。 您的代码在单个线程上运行,并包装在上述类似服务的体系结 ...
  • 我创建了一个不可见的From-object 这听起来很麻烦。 使用InvokeRequired是一种危险的反模式。 它对VB6特别致命,它的运行时严重破坏了线程处理。 您知道从工作线程调用代码,仅使用InvokeRequired验证用于同步的表单是否处于正确状态以正确执行此操作: if (!myForm.InvokeRequired()) { throw new InvalidOperationException("Synchronization window not created"); } de ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)