如何将列表中的所有术语分成两半?

时间:2019-10-22 10:31:03

标签: python list split

我需要将字符串拆分为列表,然后拆分该列表的所有术语。我一直在尝试为此创建函数,但我不知道如何实现。我正在使用此功能将字符串分成两半:

def split_case(string):
    length_string = len(string)
    first_length = round(length_string / 2)
    first_half = string[0:first_length]
    second_half = string[first_length:]
    return [first_half, second_half]

我需要做这样的事情:

def split_all(string,runs):
    ...
    return split_up

输出看起来像这样:

>>>print(split_all("Hello World!",1)
>>>["Hello ", "World!"]

'runs'参数是将字符串分割多少次,所以一是一半,二是四分之一,三是八分之一,四是十六分,依此类推。

>>>print(split_all("Spam",2)
>>>["S","p","a","m"]

>>>print(split_all("Hello World, Again!",3)
>>>["He", "llo", " W", "orl", "d,", " A", "ga", "in!"]

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

您可以递归调用以拆分字符串:

def split_str(args, runs=1):
    if not runs:
        return [args]
    else:
        runs -= 1
        h = len(args)//2
        beginning = args[:h]
        remaining = args[h:]
        return split_str(beginning, runs) + split_str(remaining, runs)

输出:

>>> split_str('Hello World!', 1)
>>> ['Hello ', 'World!']
>>> split_str('Hello World!', 2)
>>> ['Hel', 'lo ', 'Wor', 'ld!']
>>> split_str('spam', 2)
>>> ['s', 'p', 'a', 'm']

答案 1 :(得分:1)

不清楚拆分奇数长度的字符串时要做什么,例如split_case('hello')返回['hel', 'lo']['he', 'llo']吗?

下面是一个可能的解决方案,其中包含确定此行为的关键字参数:

def split_case(string, first_half_longer=True):
    string_length = len(string)
    split_length = string_length // 2
    if (string_length % 2 != 0) and first_half_longer:
        split_length += 1
    return [string[:split_length], string[split_length:]]


def split_all(string, runs, first_half_longer=True):
    original_string_list = [string]
    new_string_list = []
    for run in range(runs):
        for i in original_string_list:
            new_string_list.extend(split_case(i, first_half_longer))
        original_string_list = new_string_list
        new_string_list = []

    return original_string_list


string = "Hello World, Again!"

print(split_all(string, 3, True))
print(split_all(string, 3, False))

输出:

['Hel', 'lo', ' Wo', 'rl', 'd, ', 'Ag', 'ai', 'n!']
['He', 'll', 'o ', 'Wor', 'ld', ', A', 'ga', 'in!']

答案 2 :(得分:0)

一种方法,该方法先计算多少个子字符串,然后再累加所有子字符串。

def split_case(str, runs):
    l = len(str)
    res = []

    splitCnt = 2 ** runs
    if splitCnt >= l:
        splitCnt = l

    if (l % splitCnt == 0):
        runLen = l / splitCnt
    else:
        runLen = l / splitCnt + 1

    for i in range(0, l, runLen):
        res.append(str[i:i+runLen])

    return res

print(split_case("hello word", 2))

输出:

['hel', 'lo ', 'wor', 'd']

答案 3 :(得分:0)

使用textwrap

的简短方法
eps = tf.random_uniform( shape=[args.batchsize,1,1,1], minval=0., maxval=1.) 
X_inter = eps*train_label + (1. - eps)*gen_label 
grad = tf.gradients(discriminator_ourmethod(image=concat_image, targets=X_inter,  is_training=True ,reuse=True), [X_inter])[0] 

grad_norm = tf.sqrt(tf.reduce_sum((grad)**2, axis=[1,2,3])) 
grad_pen = 10 * tf.reduce_mean((grad_norm - 1.)**2) 
dis_loss = -tf.reduce_mean(dis_real)+tf.reduce_mean(dis_fake)+grad_pen