简体   繁体   English

Python切片字符串或添加到列表列表中的字符串

[英]Python slice strings or add to strings in list of lists

I am trying to change elements in my list of lists depending on the length of the element, if the string length is greater than 8 I want to chop the string from start to length 8, if the string is shorter than 8 I want to add however much it is shorter by in white space. 我试图根据元素的长度更改列表中的元素,如果字符串长度大于8,我想将字符串从开头切成长度8,如果字符串小于8,我想添加但是在空白处它要短得多。 Where is this code going wrong? 这段代码哪里出问题了?

list_of_lists = [['PARENT', 'ID', 'DESCRIPTION1', 'DESCRIPTION2'],
             ['', 'R1', 'R1_Des_1', '0'],
             ['C1', 'E1', 'E1_Des_1', '1'],
             ['P1', 'C1', 'C1_Des_1', '2'],
             ['R1', 'P1', 'P1_Des_1', '3'],
             ['C2', 'E2', 'E2_Des_1', '4'],
             ['P2', 'C2', 'C2_Des_1', '5'],
             ['R1', 'P2', 'P2_Des_1', '6'],
             ['P2', 'C3', 'C3_Des_1', '7'],
             ['C4', 'E3', 'E3_Des_1', '8'],
             ['P3', 'C4', 'C4_Des_1', '9'],
             ['R2', 'P3', 'P3_Des_1', '10'],
             ['None', 'R3', 'R3_Des_', '11'],
             ['P3', 'C5', 'C5_Des_1', '12'],
             ['C6', 'E4', 'E4_Des_1', '13'],
             ['P4', 'C6', 'C6_Des_1', '14'],
             ['R2', 'P4', 'P4_Des_1', '15'],
             ['C7', 'E5', 'E5_Des_1', '16'],
             ['P5', 'C7', 'C7_Des_1', '17'],
             ['R3', 'P5', 'P5_Des_1', '18'],
             ['C9', 'E6', 'E6_Des_1', '19'],
             ['P6', 'C9', 'C9_Des_1', '20'],
             ['R3', 'P6', 'P6_Des_1', '21'],
             ['P6', 'C8', 'C8_Des_1', '22'],
             ['C10', 'E7', 'E7_Des_1', '23'],
             ['P7', 'C10', 'C10_Des_1', '24'],
             ['R4', 'P7', 'P7_Des_1', '25'],
             ['P7', 'C11', 'C11_Des_1', '26'],
             ['C12', 'E8', 'E8_Des_1', '27'],
             ['P8', 'C12', 'C12_Des_1', '28'],
             ['R4', 'P8','','29'],
             ['', 'P8','','30'],
             ['R1', 'P8','','31'],
             ['', 'z1','','32'],
             ['z1', 'z2','','33'],
             ['z1', 'z3','','34'],
             ['z2', 'z4','','35'],
             ['z3', 'z4','','36']]

list_of_lists_slice = list(list_of_lists)
list_string = []

for sublist in list_of_lists_slice:
    for element in sublist:
        if len(element) > 8:
            element = element[:7]
        if len(element) < 8:
            space = 8 - len(element)
            element = element + (' ' * space)


for sublist in list_of_lists_slice:
    row_str = str(' |')
    ele_str = '|'.join(sublist)
    row_str = row_str + ele_str + ('| ')
    list_string.append(row_str)
    middle = ('  ')
    middle = middle + str((len(sublist)) * (9 * ('-')))
    list_string.append(middle)

for row in list_string:
    print (row)

I don't know what is wrong with your code, but you should definitely just use string formatting, combining the truncating and padding options of the format language: 我不知道您的代码有什么问题,但是您绝对应该只使用字符串格式,结合格式语言的截断填充选项:

>>> s1 = 'longer than 8'
>>> s2 = 'short'
>>> f'{s1:8.8}'
'longer t'
>>> f'{s2:8.8}'
'short   '

If you get a SyntaxError for these f-strings, use the old school way: 如果对于这些f字符串收到SyntaxError ,请使用传统的方法:

>>> '{:8.8}'.format(s1)
'longer t'
>>> '{:8.8}'.format(s2)
'short   '

Really, you only need two methods: string slicing and ljust . 实际上,您只需要两种方法:字符串切片和ljust Using a list-comprehension, you could do: 使用列表理解,您可以执行以下操作:

>>> new_list = [[s[:8].ljust(8, ' ') for s in sublist] for sublist in list_of_lists]

Now, let's pretty print it using pprint 现在,让我们使用pprint漂亮地打印它

>>> from pprint import pprint
>>> pprint(new_list)
[['PARENT  ', 'ID      ', 'DESCRIPT', 'DESCRIPT'],
 ['        ', 'R1      ', 'R1_Des_1', '0       '],
 ['C1      ', 'E1      ', 'E1_Des_1', '1       '],
 ['P1      ', 'C1      ', 'C1_Des_1', '2       '],
 ['R1      ', 'P1      ', 'P1_Des_1', '3       '],
 ['C2      ', 'E2      ', 'E2_Des_1', '4       '],
 ['P2      ', 'C2      ', 'C2_Des_1', '5       '],
 ['R1      ', 'P2      ', 'P2_Des_1', '6       '],
 ['P2      ', 'C3      ', 'C3_Des_1', '7       '],
 ['C4      ', 'E3      ', 'E3_Des_1', '8       '],
 ['P3      ', 'C4      ', 'C4_Des_1', '9       '],
 ['R2      ', 'P3      ', 'P3_Des_1', '10      '],
 ['None    ', 'R3      ', 'R3_Des_ ', '11      '],
 ['P3      ', 'C5      ', 'C5_Des_1', '12      '],
 ['C6      ', 'E4      ', 'E4_Des_1', '13      '],
 ['P4      ', 'C6      ', 'C6_Des_1', '14      '],
 ['R2      ', 'P4      ', 'P4_Des_1', '15      '],
 ['C7      ', 'E5      ', 'E5_Des_1', '16      '],
 ['P5      ', 'C7      ', 'C7_Des_1', '17      '],
 ['R3      ', 'P5      ', 'P5_Des_1', '18      '],
 ['C9      ', 'E6      ', 'E6_Des_1', '19      '],
 ['P6      ', 'C9      ', 'C9_Des_1', '20      '],
 ['R3      ', 'P6      ', 'P6_Des_1', '21      '],
 ['P6      ', 'C8      ', 'C8_Des_1', '22      '],
 ['C10     ', 'E7      ', 'E7_Des_1', '23      '],
 ['P7      ', 'C10     ', 'C10_Des_', '24      '],
 ['R4      ', 'P7      ', 'P7_Des_1', '25      '],
 ['P7      ', 'C11     ', 'C11_Des_', '26      '],
 ['C12     ', 'E8      ', 'E8_Des_1', '27      '],
 ['P8      ', 'C12     ', 'C12_Des_', '28      '],
 ['R4      ', 'P8      ', '        ', '29      '],
 ['        ', 'P8      ', '        ', '30      '],
 ['R1      ', 'P8      ', '        ', '31      '],
 ['        ', 'z1      ', '        ', '32      '],
 ['z1      ', 'z2      ', '        ', '33      '],
 ['z1      ', 'z3      ', '        ', '34      '],
 ['z2      ', 'z4      ', '        ', '35      '],
 ['z3      ', 'z4      ', '        ', '36      ']]
>>>

You can think of the above nested list comprehension as short-hand for the following: 您可以将上述嵌套列表理解视为以下内容的简写:

new_list = []
for sublist in list_of_lists:
    sub = []
    for s in sublist:
        sub.append(s[:8].ljust(8, ' '))
    new_list.append(sub)

Once people learn list comprehensions, they tend to overuse them. 人们一旦学会了列表理解,就会倾向于过度使用它们。 The example above is probably a borderline case, because it's becoming unreadable , and readability counts . 上面的示例可能是一个临界情况,因为它变得不可读 ,并且可读性很重要 The nested for-loops might be more appropriate. 嵌套的for循环可能更合适。

There were a few subtle bugs with your original attempt. 您最初的尝试有一些细微的错误。 I've cleaned it up and kept it to it's original spirit. 我已经将其清理干净,并保持了原始风格。 I've added comments which I hope make it obvious what was going awry. 我添加了一些评论,希望可以使出现的问题显而易见。

new_list = [] # need to build a new list!
for sublist in list_of_lists:
    sub = [] # need to build new sublists!
    for element in sublist:
        if len(element) > 8:
            sub.append(element[:8]) # slice to length 8
        else: # use else! You were skipping strings with len == 8
            space = 8 - len(element)
            sub.append(element + (' ' * space))
    new_list.append(sub)

尝试这个:

[['{:>8}'.format(x[:8]) for x in row] for row in  list_of_lists]

您可以使用此列表压缩

[i[:8] if len(i)>8 else i+[' ']*(8-len(i)) for i in list_of_lists]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM