【问题标题】:Manipulate list using index calculation使用索引计算操作列表
【发布时间】:2020-12-09 03:44:34
【问题描述】:

我有一个字符串列表:

String_list = ['Please','attach','all','the','key','content','for','each','topic']

和一个索引列表

index = [1,4]

前2个单词和后2个单词的匹配项将被标记为“key 内容”。有没有办法返回关键内容的concat字符串?

对于这个具体的例子,输出应该是:

'Please attach all the key content for'

对于索引 1:“关键内容”将是索引为 0、1、2、3 的项目(因为“附加”是列表中的第二个元素),对于索引 4,匹配索引将为 2 ,3,4,5,6。结合起来,关键内容就是上面的输出。

【问题讨论】:

  • 你能改写你的问题吗?
  • if index[0] != 0 and index[1] != len(String_list): print(' '.join(String_list[index[0]-1:index[1]+3])) else: print(' '.join(String_list[index[0]:index[1]])) 这是您要找的吗?

标签: python string list indexing concatenation


【解决方案1】:
    String_list = ['Please', 'attach', 'all', 'the', 'key', 'content', 'for', 'each', 'topic']
    index = [1,4]
    
    # get -2, +2 range string indices for each index
    str_index = [i for idx in index for i in range(idx-2, idx+3) if i >= 0 and i < len(String_list)]  
    
    # remove duplicates
    str_index = list(set(str_index))

    # get string at indices
    target_strings = [String_list[idx] for idx in str_index]

    # format into desired output and print
    print(' '.join(target_strings))


【讨论】:

    【解决方案2】:

    这是 Pythonic 的方式:

    代码:

    String_list = ['Please','attach','all','the','key','content','for','each','topic']
    index = [1,4]
    list_ind = []
    [list_ind.extend([i-2,i-1,i,i+1,i+2]) for i in index]
    res_str = ' '.join([String_list[i] for i in sorted(set(list_ind)) if i >= 0])
    print(res_str)
    

    输出:

    Please attach all the key content for
    

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      相关资源
      最近更新 更多