连接列表的某些部分。删除空格。

2024-10-03 21:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名单上的名字分开了字母,我想把个人的名字连在一起。 这就是我目前拥有的:

['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'R', 'o', 'b', ' ']

我想把它变成这样:

['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']

Tags: 字母名字steverobluke名单andrewstuart
3条回答

info成为你的清单。你知道吗

concat = "".join(info)
names = concat.split()
print names

但请看两位炼金术士的评论。你知道吗

使用^{}并使用^{}分组:

>>> from itertools import groupby
>>> lst = ['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e',  'y', ' ', 'R', 'o', 'b', ' ']
>>> [''.join(g) for k, g in groupby(lst, key=str.isspace) if not k]
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']

I am reading from a text file. I broke up the text and placed it into a list, I'm now wondering how to get it so it recognizes when a space is present and it concatenates the data accordingly. I'm not sure how though

我不知道你是怎么看这篇文章的,但你处理得不对。不要在线调用list(),也不要调用从文件中读取的全部文本:

>>> s = 'Stuart Steve Andrew Luke Shaney Luke Moley Moley Rob'
>>> list(s)
['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'R', 'o', 'b']

如果您想要一个单词列表,只需在您阅读的文本上使用^{}

>>> s.split()
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']

您可以遍历列表中的字符,下面是一个小示例:

# chars being your list
names = []

current_name = ""
for current_char in chars:
     if current_char == ' ':
         names.append(current_name)
         current_name = ""
     else:
          current_name += current_char

 return names

相关问题 更多 >