Python-仅连接列表中的相邻单词
在本文中,我们将学习如何在列表中而不是数字中连接相邻单词。请按照以下步骤解决问题。
初始化列表。
使用isalpha方法查找不是数字的单词。
4使用join方法加入单词。
通过使用isdigit方法查找所有数字,在末尾添加所有数字。
打印结果。
示例
# initialzing the list
strings = ['Tutorials', '56', '45', 'point', '1', '4']
# result
result = []
words = [element for element in strings if element.isalpha()]
digits = [element for element in strings if element.isdigit()]
# adding the elements to result
result.append("".join(words))
result += digits
# printing the result
print(result)如果运行上面的代码,则将得到以下结果。
输出结果
['Nhooo', '56', '45', '1', '4']
让我们看看使用不同方式解决问题的代码。我们将使用filter方法来过滤单词和数字。
示例
# initialzing the list strings = ['Tutorials', '56', '45', 'point', '1', '4'] def isalpha(string): return string.isalpha() def isdigit(string): return string.isdigit() # result result = ["".join(filter(isalpha, strings)), *filter(isdigit, strings)] # printing the result print(result) ['Nhooo', '56', '45', '1', '4']
如果运行上面的代码,则将得到以下结果。
输出结果
['Nhooo', '56', '45', '1', '4']
结论
如果您对本文有任何疑问,请在评论部分中提及它们。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短