[英]How to flatten a list of lists containing dates in Python
I have a list of valid dates in Python 我有Python中的有效日期列表
myList =['05-06-2015', '01-07-2015', '01-07-2015 01-07-2016', '26-08-2015', '26-08-2016', '23-06-2015 26-08-2016 01-07-2015', '06-07-2015']
As you can see, some elements have a single value, some have two and some have three dates. 如您所见,有些元素具有单个值,有些具有两个值,有些具有三个日期。
My problem is to reduce all of these into a flattened list, which looks like this: 我的问题是将所有这些减少为一个扁平的列表,如下所示:
flatList =['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016',
'26-08-2015', '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015',
'06-07-2015']
I tried to do this: 我试图这样做:
flatList = list(itertools.chain.from_iterable(myList))
But, this is not behaving as I expected and it is splitting each character as a list. 但是,这不符合我的预期,它会将每个字符拆分为一个列表。
Can you please let me know how I can accomplish this? 您能否让我知道我如何做到这一点?
Expected output: 预期产量:
flatList =['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016',
'26-08-2015', '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015',
'06-07-2015']
You need to split
each element in your original list and then flatten, eg: 您需要split
原始列表中的每个元素,然后展平,例如:
In []:
list(it.chain.from_iterable(s.split() for s in myList)
Out[]:
['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016', '26-08-2015',
'26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015', '06-07-2015']
You can split each element and then flatten the 2D list you'll have as a result, or if you want to avoid having to do the flatten bit, you could make your own loop: 您可以拆分每个元素,然后展平您将要得到的2D列表,或者,如果您希望避免进行展平,可以制作自己的循环:
newList = []
for i in myList:
newList.extend(i.split())
Although I'd like to think that this isn't very pythonic - but it's an answer none-the-less. 尽管我想这不是Python风格的-但这仍然是一个答案。
from itertools import chain
my_list = [
'05-06-2015', '01-07-2015', '01-07-2015 01-07-2016', '26-08-2015',
'26-08-2016', '23-06-2015 26-08-2016 01-07-2015', '06-07-2015'
]
flat_list = list(chain(*[x.split() for x in my_list]))
print(flat_list)
output: 输出:
['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016', '26-08-2015', '26-08-2016',
'23-06-2015', '26-08-2016', '01-07-2015', '06-07-2015']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.