区分并替换单个字符串列表元素为多个字符串列表元素

huangapple go评论62阅读模式
英文:

Differentiate and replace single for multiple string list elements

问题

要求每个列表元素都是单个字符串。第二个列表元素包含多个字符串:

suburbs = ['Wamuomata'],['Wan', 'omata'],['Eastboume']

需要修改为:

suburbs = ['Wamuomata'],['Wan omata'],['Eastboume']

代码:

suburbs = ['Wamuomata'],['Wan', 'omata'],['Eastboume']

for x in range(len(suburbs)):
    elementNumber = len(suburbs[x])
    if elementNumber > 1:
        for y in range(elementNumber):
            print(suburbs[x][y])

print(suburbs)

输出:

Wan
omata
(['Wamuomata'], ['Wan', 'omata'], ['Eastboume'])

print(suburbs[x][y]) 的输出正确引用了第二个元素的字符串。但是不知道如何进行替换。

英文:

Require each list element to be a single string. Second list element contains multiple strings:

suburbs = ['Wamuomata'],['Wan', 'omata'],['Eastboume']

Required to be:

suburbs = ['Wamuomata'],['Wan omata'],['Eastboume']

Code:

suburbs = ['Wamuomata'],['Wan', 'omata'],['Eastboume']

for x in range(len(suburbs)):
        elementNumber = len(suburbs[x])
        if elementNumber > 1:
            for y in range(elementNumber):
                print(suburbs[x][y])
                
                    

print(suburbs)

Output:

Wan
omata
(['Wamuomata'], ['Wan', 'omata'], ['Eastboume'])

The output from print(suburbs[x][y]) references the list strings of element two correctly. However don't know how to replace.

答案1

得分: 1

你可以在每个列表上使用 str.join 将其转化为单个字符串:

>>> suburbs = ['Wamuomata'], ['Wan', 'omata'], ['Eastboume']
>>> tuple([' '.join(s)] for s in suburbs)
(['Wamuomata'], ['Wan omata'], ['Eastboume'])

请注意,如果你想要得到一个字符串的单一列表,而不是每个字符串都在一个单独的列表中,更简单的方式是:

>>> [' '.join(s) for s in suburbs]
['Wamuomata', 'Wan omata', 'Eastboume']
英文:

You can use str.join on each list to turn it into a single string:

>>> suburbs = ['Wamuomata'],['Wan', 'omata'],['Eastboume']
>>> tuple([' '.join(s)] for s in suburbs)
(['Wamuomata'], ['Wan omata'], ['Eastboume'])

Note that if you want a single list of strings, as opposed to a tuple of lists of a single string each, it's simpler:

>>> [' '.join(s) for s in suburbs]
['Wamuomata', 'Wan omata', 'Eastboume']

答案2

得分: 1

你可以在for循环内使用join函数来连接每个索引中的所有单词。

new_suburbs = [' '.join(word) for word in suburbs]

英文:

You can use the join function inside for loop to join all words in each index

new_suburbs = [' '.join(word) for word in suburbs]

huangapple
  • 本文由 发表于 2023年6月19日 11:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定