我有一个清单清单。看起来像这样:
user
我要进行迭代,以便在每次迭代时从所有列表中获取该索引的相应元素,如果列表为空,则将其删除。
例如,当索引为0时,我想要一个列表,该列表将从列表1的列表0.5扩展(添加)4从列表1的100扩展到列表2(所有列表的第0个索引),并且如果列表为空(例如列表3在第3次迭代后将被完全覆盖,请跳过该列表。因此迭代应跳过此列表并移至下一个列表。
所以输出应类似于:[
[4,7,9,10],
[5,14,55,24,121,56, 89,456, 678],
[100, 23, 443, 34, 1243,]
....
]
我想要一个扩展这些值的列表。
答案 0 :(得分:4)
zip_longest
是有问题的,因为任何解决方案都会在输入中出现fillvalue
时自动丢弃roundrobin
(这可以解决,但是总会有些麻烦)。
最通用的解决方案是来自the itertools
module的from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
食谱:
mylist = [
[4,7,9,10],
[5,14,55,24,121,56, 89,456, 678],
[100, 23, 443, 34, 1243,]
....
]
print(list(roundrobin(*mylist)))
对于您的输入,您将执行以下操作:
import java.util.Scanner;
public class Insurance
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter current year: ");
int CurrentYear = scan.nextInt();
System.out.println("Enter birth year: ");
int BirthYear = scan.nextInt();
System.out.println("Premium amount is: $" + PremiumAmount);
calculatePremium(CurrentYear, BirthYear);
}
public static int calculatePremium(int CurrentYear, int BirthYear)
{
int decade = (CurrentYear - BirthYear)/10;
double PremiumAmount = (decade +15)*20;
return PremiumAmount;
}
}
答案 1 :(得分:3)
您可以使用itertools.zip_longest()
(它是标准库的一部分,并且是内置zip()
的替代品,后者将其输出截短为最短的参数)来重新排序/旋转列表,然后使用双重列表推导来展平该输出。
from itertools import zip_longest
inp = [
[4,7,9,10],
[5,14,55,24,121,56, 89,456, 678],
[100, 23, 443, 34, 1243,]
]
output = [
elem
for tup in zip_longest(*inp) # if we don't provide a fillvalue...
for elem in tup # ...missing elements are replaced with None...
if elem is not None # ...which we can filter out
]
# [4, 5, 100, 7, 14, 23, 9, 55, 443, 10, 24, 34, 121, 1243, 56, 89, 456, 678]
答案 2 :(得分:0)
一个简单的事情就是通过添加一个已知值,将给定列表转换为大小相等的列表。然后,我们可以对其进行迭代,并仅在该元素不是已知值时才添加结果。
like