简体   繁体   English

Python - 将具有不同大小的列表的数组转换为字符串

[英]Python - Convert array with list with different sizes to string

I have a Python array that contains a lot of lists, with different sizes. 我有一个包含大量不同大小的列表的Python数组。

myArray = [('Hello my name is ', ('Bond, James', 'Bond. It is ', '16:40', ' now'), '!!!')]

Question: What is the best way (more optimized) to get the bellow output, without creating a loop method which will append every value to a string? 问题:获得波纹管输出的最佳方法(更优化)是什么,而不创建将每个值附加到字符串的循环方法?

I would like to see the following output: 我想看到以下输出:

"Hello my name is Bond, James Bond. It is 16:40 now!!!"

First, you have to flatten the nested list to a 'flat' list. 首先,您必须将嵌套列表展平为“平面”列表。 Assuming that your list contains either strings or other lists (or tuples), you could use a function like this: 假设您的列表包含字符串或其他列表(或元组),您可以使用如下函数:

def flatten(lst):
    for x in lst:
        if isinstance(x, str):
            yield x
        else:
            for y in flatten(x):
                yield y

Incidentally, there also seems to be a function for this in the compiler.ast module, so alternatively you could just import that function and use it. 顺便说一下,在compiler.ast模块中似乎也有一个函数,所以你也可以导入该函数并使用它。 However, this module is deprecated and has been removed in Python 3. 但是,此模块已弃用,已在Python 3中删除。

from compiler.ast import flatten

Either way, after the list has been flattened, you just have to join the segments to one string. 无论哪种方式,在列表被展平后,您只需将段加入一个字符串即可。

>>> list(flatten(myArray))
['Hello my name is ', 'Bond, James', 'Bond. It is ', '16:40', ' now', '!!!']
>>> ''.join(flatten(myArray))
'Hello my name is Bond, JamesBond. It is 16:40 now!!!'

You can write a very comprehensive recursive function like the one I wrote - 你可以编写一个非常全面的递归函数,就像我写的那样 -

In [1]: def solve(x):
            if isinstance(x, str):
                return x
            return ''.join(solve(y) for y in x)

In [2]: solve(myArray)
Out[2]: 'Hello my name is Bond, JamesBond. It is 16:40 now!!!'

Here is a variation which joins as it flattens: 这是一个随着它变平而加入的变体:

def deepJoin(stuff,d = ' '):
    if isinstance(stuff,str):
        return stuff
    else:
        return d.join(deepJoin(x,d) for x in stuff)

For example: 例如:

>>> deepJoin( [('Hello my name is ', ('Bond, James', 'Bond. It is ', '16:40', ' now'), '!!!')])
'Hello my name is  Bond, James Bond. It is  16:40  now !!!'

Another option is to use a list comprehension to flatten the list: 另一种选择是使用列表推导来展平列表:

bond_says = ["".join(item) for sublist in myArray for item in sublist] # list comprehension
print(" ".join(bond_says))

Output: 输出:

"Hello my name is  Bond, JamesBond. It is 16:40 now !!!"

You could use regex (python 2.7): 你可以使用正则表达式(python 2.7):

import re
myArray = [('Hello my name is ', ('Bond, James', 'Bond. It is ', '16:40', ' now'), '!!!')]
print re.sub("(?:^|')[^']+(?:'|$)", '',str(myArray))

[Output]

Hello my name is Bond, JamesBond. It is 16:40 now!!!

UPDATE UPDATE

Try this with myArray= [('Won\\'t work with this.')] – tobias_k 7 hours ago 尝试使用myArray = [('不会用这个。')] - tobias_k 7小时前

import re
p = r"(?:^|(?<!\\)')[^'\"\\]+(?:'|$)|(?:^|\")[^\"]+(?:\"|$)"

myArray = [('Hello my name is ', ('Bond, James', 'Bond. It is ', '16:40', ' now'), '!!!')]
myArray2= [('Won\'t work with this.')]

print (re.sub(p, '', str(myArray)))
print (re.sub(p, '', str(myArray2)))

[Output]

Hello my name is Bond, JamesBond. It is 16:40 now!!!
Won't work with this.

A map makes it pretty concise: map使它非常简洁:

def flatten(arr):
    if type(arr) == str:
        return arr.strip()
    else:
        return " ".join(map(flatten, arr))

returns "Hello my name is Bond, James Bond. It is 16:40 now !!!" 返回“你好我的名字是邦德,詹姆斯邦德。现在是16:40 !!!” for the example. 例如。

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

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