英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论