简体   繁体   English

function 使用元组列表转换字符串列表?

[英]function that transforms a list of strings using a list of tuples?

I want to make a function that takes in a list of strings and a list of tuples as inputs.我想制作一个 function,它将字符串列表和元组列表作为输入。 It then reacts to keywords in the list of tuples to modify the list of strings.然后它对元组列表中的关键字作出反应以修改字符串列表。 the function should look like transform('stringlist','tuplelist') function 应该看起来像transform('stringlist','tuplelist')

For example, suppose we use the stringlist is ['cloud', 'terra']例如,假设我们使用的字符串列表是['cloud', 'terra']

here is how the different tuples will affect the string list:以下是不同的元组将如何影响字符串列表:

('uppercase', n) will change every nth letter in the list of strings to uppercase. ('uppercase', n)会将字符串列表中的每个第 n 个字母更改为大写。 ex.前任。 transform(['cloud','terra'], [('uppercase', 2)]) will return ['cLoUd','tErRa'] transform(['cloud','terra'], [('uppercase', 2)])将返回['cLoUd','tErRa']

('first',n) will split the list so only the first n letters are present. ('first',n)将拆分列表,因此只有前 n 个字母出现。 ex.前任。 transform(['cloud','terra'], [('first',3)]) will return ['clo','ter'] transform(['cloud','terra'], [('first',3)])将返回['clo','ter']

('last',n) will split the list so only the last n letters are present. ('last',n)将拆分列表,因此只有最后 n 个字母存在。 ex.前任。 transform(['cloud','terra'], [('last', 3)]) will return ['oud','rra'] transform(['cloud','terra'], [('last', 3)])将返回['oud','rra']

('insert', n, x) will insert a string in the list's nth index. ('insert', n, x)将在列表的第 n 个索引中插入一个字符串。 ex.前任。 transform(['cloud','terra'], [('insert', 1, 'zidane')]) will return ['cloud','zidane','terra'] transform(['cloud','terra'], [('insert', 1, 'zidane')])将返回['cloud','zidane','terra']

('delete', n) will delete the nth index in the list. ('delete', n)将删除列表中的第 n 个索引。 ex.前任。 transform(['cloud','terra'], [('delete', 0)]) will return ['terra'] transform(['cloud','terra'], [('delete', 0)])将返回['terra']

('length',n) . ('length',n) If the length of a string is greater than n, then str(len(examplestr)) will be placed in the middle of examplestr.如果一个字符串的长度大于 n,那么 str(len(examplestr)) 将被放在 examplestr 的中间。 If examplestr cannot be split in half evenly, then it will use the position of len(examplestr)/2 rounded down the nearest whole number.如果 examplestr 不能平分,那么它将使用 len(examplestr)/2 的 position 向下舍入最接近的整数。 ex.前任。 transform(['cloud','terra'], [('length', 2)]) will return ['cl5oud','te5rra'] transform(['cloud','terra'], [('length', 2)])将返回['cl5oud','te5rra']

if a list is comprised of multiple tuples, it should look like:如果一个列表由多个元组组成,它应该看起来像:

transform(['cloud','terra'],[('last',2),('delete',0)]) 

which outputs ['ra']输出['ra']

What I'm Trying我在尝试什么

for i in range(len(tuplelist)):
    if 'last' in tuplelist[i]:
        output = [j[((tuplelist[i])[1]-1):] for j in stringlist]
output

this excerpt takes in:这段摘录包含:

stringlist = ['cloud','terra']
tuplelist = [('last',3)]

as inputs and outputs ['oud', 'rra'].作为输入和输出 ['oud', 'rra']。 This is mainly a proof of concept and I wanted to see if it would be possible to modify the string using only if statements and for loops.这主要是一个概念证明,我想看看是否可以仅使用 if 语句和 for 循环来修改字符串。 However, I would like to see if this function could be done using lambda and list comprehension without the use of imports.但是,我想看看这个 function 是否可以在不使用导入的情况下使用 lambda 和列表理解来完成。

I think what you need is something like this.我想你需要的是这样的东西。 See comments for details.详情见评论。

from functools import reduce

class Transformer:
    # define some transformer functions.
    # lambda is a short cut, but better to write independent functions.
    uppercase = lambda str_list, n: [str.replace(d, d[n], d[n].upper(), 1) for d in str_list]
    first = lambda str_list, n: [d[:n] for d in str_list]
    last = lambda str_list, n: [d[-n:] for d in str_list]
    insert = lambda str_list, n, x: str_list.insert(n, x)

    # Add  more functions as you need them

    # define a function to transform a list of strings using a function and its args
    @staticmethod
    def _transform_exec(str_list, transformer):
        func, args = transformer[0], transformer[1]
        return func(str_list, *args)

    @staticmethod
    def transform(str_list, *transformers):
        # Collect the string list and function list
        transformer_list = []
        for transformer in transformers:
            # for each transformer str, find the function delegate and its args
            _transformer = getattr(Transformer, transformer[0])
            transformer_list.append([_transformer, transformer[1:]])
        
        # run a pipeline of transformers
        return reduce(Transformer._transform_exec, transformer_list, str_list)


if __name__ == '__main__':
    res = Transformer.transform(['cloud', 'terra'], ('uppercase', 1), ('first', 3), ('last', 1))
    print(res)

This produces an output这会产生一个 output

['o', 'r']

The approach is only to create a pipeline of different functions using the reduce .该方法只是使用reduce创建不同功能的管道。 This is only an example to demonstrate the possible appraoch.这只是一个演示可能方法的示例。 You will have to work to make it robust你将不得不努力让它变得健壮

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

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