我通过读取文件中的制表符分隔值(每行一个列表)来生成6项列表。一些制表符分隔的值是空的(零长度)或不存在的(例如,一行上只有4个值)。对于这种情况,我可以使用if-else循环来使新列表的元素采用我在“模板”列表中定义的某些默认值,但最简单的方法是什么?
template_list = [0, 0, 'X', 0, 'Y', 'Z']
...
new_data = line.strip().split('\t')
...
new_list = new_data
答案 0 :(得分:1)
将行已经分割成字段(例如,源自csv.reader)可以将其削减为单行列表理解。
template_tuple = (0, 0, 'X', 0, 'Y', 'Z')
template_tuple_len = len(template_tuple)
def extract_normalized_fields_from_row(row):
split_row = row.strip().split('\t')
return [v if len(v) else template_tuple[i] for (i, v) in enumerate(
split_row + [''] * (template_tuple_len - len(split_row)))]
for row in (
'\t'.join(('1', '2', '3', '4', '5', '6')),
'\t'.join(('1', '', '3', '4', '5', '6')),
'\t'.join(('1', '2', '3', '4'))
):
print extract_normalized_fields_from_row(row)
在眼睛上有点不安,代码的以下部分仅用于右键填充split_row,其长度等于template_tuple的任何数量的空字符串元素是必需的。这假设所有行字段(包括从短行中提取的字段)都相对于template_tuple左对齐。
split_row + [''] * (template_tuple_len - len(split_row))
输出:
['1', '2', '3', '4', '5', '6']
['1', 0, '3', '4', '5', '6']
['1', '2', '3', '4', 'Y', 'Z']
另外,对于我的味觉来说有点过于密集,单线会产生相同的输出:
template_tuple = (0, 0, 'X', 0, 'Y', 'Z')
template_tuple_len = len(template_tuple)
for row in (
'\t'.join(('1', '2', '3', '4', '5', '6')),
'\t'.join(('1', '', '3', '4', '5', '6')),
'\t'.join(('1', '2', '3', '4'))
):
print [v if len(v) else template_tuple[i] for split_row in
(row.strip().split('\t'),) for (i, v) in enumerate(
split_row + [''] * (template_tuple_len - len(split_row)))]
答案 1 :(得分:1)
template_list = [0, 0, 'X', 0, 'Y', 'Z']
def read_from(line):
new_data = line.split('\t',5)
full_data = []
i = 0
for a in new_data:
if len(a) < 1:
a = template_list[i]
i = i + 1
full_data.append(a)
return full_data
# I assumed that you have 5 tab delimeters for your 6 items but
# some of the locations have no data between delimiters
# and the intent is that they then take a default value
print read_from('11\t\tV\t4\t\tT')
print read_from('\t42\tR\t3\tV\tT')
print read_from('\t\t\t\t\t')
示例输出:
['11',0,'V','4',0,'T']
[0,'42','R','3','V','T']
[0,0,'X',0,'Y','Z']