简体   繁体   中英

how to slice strings with the help of a list of tuples?

I have a list of tuples as as follows:

list_1 = [(2,10), (3,13), (5,23)]

and also a list of strings as follows:

list_2 = [ATGCATGCGAGTGCGAGTGCGTGCGTGCAGTGCGAGTGC,
          ATCGTCGTCGACGTAGCTAGCTAGCTAGCTAGCTAS,
          ATGCGTACGATCGATCGATCGATCGATCGAGCTAGCTAGCT]

I want to slice the list of strings with the help of given tuple integer gaps. For example;

I want to slice the first string from indexes 2 and 10 and print out only the letters which belong to those indexes. So the result print will be as 'GCATGCGAG'.

For the second string it should slice and select the indexes from 3-13.so the result should be 'GTCGTCGACGTAG'. This should go on. Can somebody suggest me a code for this. Thanks in advance.

A straightforward solution is to zip the two lists and use tuple elements from one list as slice parameters for the other:

[l2[l1[0] : l1[1] + 1] for l1, l2 in zip(list_1, list_2)]
#['GCATGCGAG', 'GTCGTCGACGT', 'TACGATCGATCGATCGATC']

If the second element of a tuple were the next element after the end of the subsequence (which is a "normal" Python convention), you could get an even more elegant solution:

[l2[slice(*l1)] for l1, l2 in zip(list_1, list_2)]
#['GCATGCGA', 'GTCGTCGACG', 'TACGATCGATCGATCGAT']

You can use the function map :

list_1 = [(2,10), (3,13), (5,23)]

list_2 = ['ATGCATGCGAGTGCGAGTGCGTGCGTGCAGTGCGAGTGC',
          'ATCGTCGTCGACGTAGCTAGCTAGCTAGCTAGCTAS',
          'ATGCGTACGATCGATCGATCGATCGATCGAGCTAGCTAGCT']

list(map(lambda idx, lst: lst[idx[0]: idx[1]+1], list_1, list_2))
# ['GCATGCGAG', 'GTCGTCGACGT', 'TACGATCGATCGATCGATC']

use it to do what you want: string[num1:num2]

To print them all, you need this:

for i in range(len(list_1)):
    print(list_2[i][list_1[i][0]:list_1[i][1] +1])

hopefully the problem is solved,

Have a Good Code :)

You can use list comprehension to achieve this :

list_3 = [item[list_1[int(index)][0]:list_1[int(index)][1]] for index,item in enumerate(list_2)]

Above code will take one element from list_2 to item and use it index and use that in list_1 and than slice item according to tuple of list_1.

How it work :

  1. Take item one by one from list_2
  2. take tuple from list_1 using index
  3. slice item using tuple
  4. store it in list_3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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