在powershell中以循环方式向数组中添加项



我正在启动一个项目,其中将输入一个具有基本名称的.csv文件。我需要遍历这个.csv中的所有名称,并将它们添加到最大限制为20的列表/数组中。此外,如果该名称已在列表中,则需要移动到下一个列表中。但是,需要制作的列表/数组的数量是基于csv的总计数。一个名字的输入次数没有限制,但我需要在所有数组中循环使用,这样名字的间隔就均匀了。

因此,我需要类似于如果($CSVfilenames.count=<80(将生成4个数组,并以循环方式添加名称。

最好使用多维数组吗?或者任何人都可以更好地选择如何开始。我真的很困惑该如何开始,我尝试的最初几件事导致了灾难。

动力外壳还是很新的。

这里有一个基于哈希表的快速草案。首先,计算需要多少组。将输入的大小除以组大小并向上取整。然后创建用于存储元素的集合。循环输入并将每个元素存储到集合中。

缺少的是如何处理重复项。很容易查找是否存在,因为哈希表有.ContainsKey()方法。如何从哈希表中提取另一个哈希表的逻辑留给读者练习。

此解决方案不保留原始顺序,因为哈希表定义为无序集合。还有有序字典,可以通过类型加速器[ordered]访问。

# Some test cases
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'chives', 'sage', 'fennel', 'oregano', 'thyme', 'tarragon', 'rosemary') # 11 unique elements
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'chives', 'sage', 'fennel', 'oregano', 'thyme', 'tarragon', 'rosemary', 'laurel') # 12 unique elements
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'parsely', 'chives', 'sage', 'fennel', 'oregano', 'thyme', 'tarragon', 'rosemary') # 12 elements, one duplicate, good index
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'chives', 'sage', 'fennel', 'parsely', 'oregano', 'thyme', 'tarragon', 'rosemary') # 12 elements, one duplicate, bad index
# How big a group will be
$groupMaxSize = 4
# Divide list size with group size and round up
# This many groups are needed
$numGroups = [math]::ceiling($data.Count / $groupMaxSize)
# Create hash table for each group. Store in an array
$hh = @()
for($i=0;$i -le $numGroups; ++$i) {
$hh += @{}
}
# Iterate through the data. Each element index mod numGroups will tell
# into which group it will belong.
for($i=0;$i -lt $data.Count; ++$i) {
# Which group will the element go into?
$idx = $i % $numGroups
# Hashtable requires unique keys, so only add elements that don't exist.
# Key is the data, value is group index.
if(-not $hh[$idx].ContainsKey($data[$i])) {
$hh[$idx].Add($data[$i], $idx)
} else {
# Element alreayd existed, add logic to look up next free hashtable
write-host "collision!" $data[$i]
} 
}
# print results
$hh
collision!  parsely
Name                           Value
----                           -----
basil                          0
chives                         0
oregano                        0
thyme                          1
marjoram                       1
sage                           1
aniseed                        2
fennel                         2
tarragon                       2
rosemary                       3
parsely                        3

最新更新