简体   繁体   English

列表中项目的条件子字符串 (Python)

[英]Conditional substring of items in a list (Python)

I have 2 lists.我有 2 个列表。 The first is my data list, and the second is a list of randomly generated numbers:第一个是我的数据列表,第二个是随机生成的数字列表:

alist = ['ABCDEF', 'GHIJKL', 'MNOPQR', 'STUVWX']
blist = [2,0,3,1]

I want to substring 3 characters from each item in alist based on the values from blist .我想根据blist 中的值从alist 中的每个项目中提取 3 个字符。

My desired outcome:我想要的结果:

['CDE', 'GHI', 'PQR', 'TUV']

How can I substring X characters from one list based on starting motif locations described in a different list?如何根据不同列表中描述的起始主题位置从一个列表中子串 X 个字符?

Edit:编辑:

The following function accomplishes my desired outcome, but is there a better way to accomplish this task?下面的函数实现了我想要的结果,但是有没有更好的方法来完成这个任务?

x = -1
clist = []
for i in alist:
    tracker = 1
    x = x + tracker
    substring = i[blist[x]:blist[x]+3]
    clist.append(substring)

Here is a solution:这是一个解决方案:

output = []
for x in range(len(alist)):
    index = blist[x]
    output.append(alist[x][index:index+3])

How this program works:该程序的工作原理:

First, it runs through the loop for the length of alist.首先,它在循环中运行 alist 的长度。 The index position that you want to analyze is the x value of blist.你要分析的索引位置是blist的x值。 Finally, append to an output list the first three characters from the index position in alist.最后,将 alist 中索引位置的前三个字符附加到输出列表。

You can define a function to do this and make use of the built-in enumerate() .您可以定义一个函数来执行此操作并使用内置的enumerate()


alist = ['ABCDEF', 'GHIJKL', 'MNOPQR', 'STUVWX']
blist = [2, 0, 3, 1]


def substring_picker(list_a, list_b):
    # first create an empty list
    results = []

    # then loop over alist
    for i, element in enumerate(alist):
        # only pick elements with at least 3 chars
        if len(alist[i]) >= 3:
            # append the found chars to results list
            results.append(list_a[i][list_b[i]:list_b[i] + 3])

    return results


result = substring_picker(alist, blist)
print(result)

使用zip将每个“计数”与要缩短的项目链接的简短列表理解,然后使用索引运算符来选择和修剪字符串:

 [x[0][x[1]:][:3] for x in zip(alist, blist)]

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

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