首页 > 解决方案 > 如何从python3中的子列表访问零索引和日期索引之间的元素?

问题描述

如何从python3中的子列表访问零索引和日期索引之间的元素?

查找第零个索引和日期索引之间的元素。之后,连接这些元素。并保存在一个列表中。之后将 concat 元素插入到子列表中的第一个索引并删除拆分的元素。

import re
nested_list =[["1","a","b","22/01/2014","variable"],["2","c","d"], 
["3","e","f","23/01/2014","variable"]]
sub_list=[]
for i in range(0,len(nested_list)):
    concat = ''
    data_index = ''
for j in range(0,len(nested_list[i])):
    temp = re.search("[\d]{1,2}/[\d]{1,2}/[\d]{4}", nested_list[i][j])
    if temp:
        date_index = j              
if date_index:
    for d in range(1,date_index):
        concat = concat+' '+ nested_list[i][d]
    print(concat)

预期输出:

nested_list =[["1","a b","22/01/2014","variable"],["2","c","d"],["3","e f","23/01/2014","variable"]]

标签: python

解决方案


那么你

想要日期和第零索引之间的元素,这就是为什么 ["2","c","d"] 我没有结合这些元素 t@Patrick Artner

干得好:

import re
nested_list =[["1","a","b","22/01/2014"],["2","c","d"], ["3","e","f","23/01/2014"]]

result = []
for inner in nested_list:
    if re.match(r"\d{1,2}/\d{1,2}/\d{4}",inner[-1]):  # simplified regex
        # list slicing to get the result
        result.append( [inner[0]] + [' '.join(inner[1:-1])] + [inner[-1]] )
    else:
        # add as is
        result.append(inner)

print(result) 

输出:

[['1', 'a b', '22/01/2014'], ['2', 'c', 'd'], ['3', 'e f', '23/01/2014']]

编辑因为日期也可能发生在两者之间 - 原始问题数据未涵盖的内容:

import re
nested_list =[["1","a","b","22/01/2014"], ["2","c","d"], 
              ["3","e","f","23/01/2014","e","f","23/01/2014"]]

result = []
for inner in nested_list:
    # get all date positions
    datepos = [idx for idx,value in enumerate(inner) 
               if re.match(r"\d{1,2}/\d{1,2}/\d{4}",value)] 

    if datepos:
        # add elem 0
        r = [inner[0]]
        # get tuple positions of where dates are
        for start,stop in zip([0]+datepos, datepos):
            # join between the positions 
            r.append(' '.join(inner[start+1:stop]))
            # add the date
            r.append(inner[stop])
        result.append(r)
        # add anything _behind_ the last found date
        if datepos[-1] < len(inner):
            result[-1].extend(inner[datepos[-1]+1:])
    else:
        # add as is
        result.append(inner)

print(result) 

输出:

[['1', 'a b', '22/01/2014'], 
 ['2', 'c', 'd'], 
 ['3', 'e f', '23/01/2014', 'e f', '23/01/2014']]

推荐阅读