我有一个上传的文件,显示
汉33.3
韩5.66
韩8.3 Chewbacca 99.4
Chewbacca 100.3
Chewbacca 98.1
我需要使用字典为每个汉和Chewbacca制作一个平均值,但首先我必须拆分列表才能做到这一点。如何为此目的拆分它们。
答案 0 :(得分:0)
我假设名称和数量之间的空格是单个空格。我也称我的价值观为“得分”,Han和Chewbacca为“我的示例解决方案”。结果将行拆分为单独的键值对;每个键代表找到的值列表;它:
Imports System.IO
Dim pathToYourFile As String = "Path to your file with file name"
Dim f As StreamReader = File.OpenText(pathToYourFile)
Dim fileText As String = f.ReadToEnd
f.Close()
Dim singleSpace As String = " " 'single space between quotes
Dim playerScores As New SortedDictionary(Of String, List(Of Double))
Dim lines() As String = fileText.Split(vbCrLf.ToCharArray())
For i As Integer = 0 To lines.Length - 1
Dim scoreLine() As String = lines(i).Split(" ".ToCharArray())
Dim playerName As String = scoreLine(0)
Dim score As Double = Double.Parse(scoreLine(1))
If playerScores.ContainsKey(playerName) Then
playerScores(playerName).Add(score)
Else
Dim list As New List(Of Double)
list.Add(score)
playerScores.Add(playerName, list)
End If
Next i
答案 1 :(得分:0)
试试这个:
Public Class DataClass
Public Property Name() As String
Public Property Value() As Decimal
End Class
' ...
Public Shared Function GetAverageDict(lines As IEnumerable(Of String)) _
As Dictionary(Of String, Decimal)
Dim lst As New List(Of DataClass)()
For Each line As String In lines
Dim lastSpaceIndex = line.LastIndexOf(" ")
If (lastSpaceIndex >= 0) Then
Dim name = line.Substring(0, lastSpaceIndex).Trim()
Dim value = Decimal.Parse(line.Substring(lastSpaceIndex + 1), _
System.Globalization.CultureInfo.InvariantCulture)
lst.Add(New DataClass() With { .Name = name, .Value = value })
End If
Next
Dim averages = From g In From x In lst _
Group x By key = x.Name _
Select New With { .Name = key, _
.Average = Group.Average(Function(y) y.Value) }
Return averages.ToDictionary(Function(x) x.Name, Function(y) y.Average)
End Function
该函数首先从每一行获取部件。它假定最后一个空格是各部分之间的分隔符。这样,名称也可以包含空格字符。
数据收集在一个列表中,然后按名称分组。通过调用ToDictionary
,分组操作的结果将转换为字典。
像这样调用函数:
Dim dict = GetAverageDict(System.IO.File.GetLines(filePath))