[英]remove the last two characters from strings in list using python
I have a very complicated problem.我有一个非常复杂的问题。 At least my python skills are not enough to solve it and I need help or at least ideas on how to solve this problem.
至少我的 Python 技能不足以解决它,我需要帮助或至少关于如何解决这个问题的想法。
I have a huge list of words that looks like this:我有一大串看起来像这样的单词:
words_articles=['diao','carrosos', 'cidadea', cidadesas']
I need to append into another list the last or the last two characters of each string into a new list, because they are these words' articles: 'a', 'o', 'as', 'os'我需要将每个字符串的最后或最后两个字符附加到另一个列表中,因为它们是这些单词的文章:'a'、'o'、'as'、'os'
my result should be two lists like the following:我的结果应该是两个列表,如下所示:
words=['dia','carros', 'cidade', 'cidades']
articles=['o', 'os','a','as']
I have no idea how to solve this.我不知道如何解决这个问题。 I just know that I have to loop through each string but from this stage on I don't know what to do.
我只知道我必须遍历每个字符串,但从这个阶段开始我不知道该怎么做。
words_articles=['diao','carrosos', 'cidadea', 'cidadesas']
words=[]
articles=[]
for y in words:
for x in y:
What should I do next after this?这之后我应该怎么做?
You can test the last letter你可以测试最后一个字母
words_articles=['diao','carrosos', 'cidadea', 'cidadesas']
words=[]
articles=[]
for word in words_articles:
if word[-1] == 's':
words.append(word[:-2])
articles.append(word[-2:])
else:
words.append(word[:-1])
articles.append(word[-1:])
print(words)
print(articles)
Out:出去:
['dia', 'carros', 'cidade', 'cidades']
['o', 'os', 'a', 'as']
You probably want the 'words' and 'articles' variables to be sets to prevent duplication:你可能想的“话”和“文章”变量是套以防止重复:
words_articles=['diao','carrosos', 'cidadea', 'cidadesas']
words=set()
articles=set()
for word in words_articles:
suffix_size = 2 if word.endswith("s") else 1
words.add(word[:-suffix_size])
articles.add(word[-suffix_size:])
Output would be:输出将是:
{'carros', 'cidade', 'dia', 'cidades'}
{'a', 'as', 'os', 'o'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.