python - 如何从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"]]
解决方案
那么你
想要日期和第零索引之间的元素,这就是为什么 ["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']]
推荐阅读
- ruby-on-rails - Unicorn 不同控制器动作的不同超时
- java - 从另一个数组创建一个数组?
- javascript - Google Web App 无法使用基本的 Javascript 请求
- python - Python:打开文件和其中的行出现问题
- java - BlockingQueue - 一个生产者多个消费者
- linux - pdf2htmlEX 转换文本但不可见(程序在 linux 上找不到字体文件?)
- javascript - WKWebView Javascript 不会为屏幕下方的对象加载 - Swift
- blazor - 当子组件更改父组件值时,Blazor 运行自定义事件
- r - 在两个不同的数据框中复制给定列的顺序
- java - 如何确保 Java 中的内存可见性?