首页 > 解决方案 > 在 Python 中修改列表中的字符串

问题描述

我想创建一个从这个转换列表的程序:

['H.Geffner/AI:FromProgramstoSolvers7', 'R.DeSousa.', 'R.Dechter.', 'H.Dreyfus.', 'J.Elster.', 'J.Evans.Dual-processingaccountsofreasoning,judgment,', 'H.Geffner.Heuristics,planning,cognition.InR.Dechter,', 'H.Geffner,andJ.Y.Halpern,editors,', 'H.Geffner.Computationalmodelsofplanning.', 'M.Genesereth,N.Love,andB.Pell.Generalgameplay-', 'G.Gigerenzer.', 'G.GigerenzerandP.Todd.', 'A.Gopnik,C.Glymour,D.Sobel,L.Schulz,T.Kushnir,and']

对此:

['H.Geffner', 'R.DeSousa', 'R.Dechter', 'H.Dreyfus', 'J.Elster', 'J.Evans', 'H.Geffner', 'H.Geffner', 'H.Geffner', 'M.Genesereth', 'G.Gigerenzer', 'G.Gigerenzer', 'A.Gopnik', 'C.Glymour', 'D.Sobel', 'L.Schulz', 'T.Kushnir']

所有名称都用“.”、“and”或“,”与其他信息隔开

我尝试通过计算“。”的数量来将它们分开。它有,当它达到 2 时,它会将该项目附加到一个没有额外信息的新列表中,但我认为可能有不同的方法。

这就是我到目前为止所得到的。

names = (the huge list I showed above)
just_names = []
current_name = ""
number_of_periods = 0
for item in names:
    index = 0
    while index < 8:
        if item[index] != ".":
            current_name = current_name + item[index]
           # print(current_name)
            index = index + 1
        else:
            number_of_periods= number_of_periods+ 1
            index = index + 1
            if ponto >= 2:
                just_names.append(current_name)
                current_name = ""

标签: python

解决方案


import re

names=['H.Geffner/AI:FromProgramstoSolvers7', 'R.DeSousa.', 'R.Dechter.', 'H.Dreyfus.', 'J.Elster.', 'J.Evans.Dual-processingaccountsofreasoning,judgment,', 'H.Geffner.Heuristics,planning,cognition.InR.Dechter,', 'H.Geffner,andJ.Y.Halpern,editors,', 'H.Geffner.Computationalmodelsofplanning.', 'M.Genesereth,N.Love,andB.Pell.Generalgameplay-', 'G.Gigerenzer.', 'G.GigerenzerandP.Todd.', 'A.Gopnik,C.Glymour,D.Sobel,L.Schulz,T.Kushnir,and']
just_names=[]
for name in names:
    found=re.findall('[A-Z]\.[A-Za-z]+',name)
    for n in found:
        just_names.append(n)
print(just_names)

或 1 行答案:

import re

names=['H.Geffner/AI:FromProgramstoSolvers7', 'R.DeSousa.', 'R.Dechter.', 'H.Dreyfus.', 'J.Elster.', 'J.Evans.Dual-processingaccountsofreasoning,judgment,', 'H.Geffner.Heuristics,planning,cognition.InR.Dechter,', 'H.Geffner,andJ.Y.Halpern,editors,', 'H.Geffner.Computationalmodelsofplanning.', 'M.Genesereth,N.Love,andB.Pell.Generalgameplay-', 'G.Gigerenzer.', 'G.GigerenzerandP.Todd.', 'A.Gopnik,C.Glymour,D.Sobel,L.Schulz,T.Kushnir,and']
just_names=[n for l in [re.findall('[A-Z]\.[A-Za-z]+',name) for name in names] for n in l]
print(just_names)

输出:

['H.Geffner', 'R.DeSousa', 'R.Dechter', 'H.Dreyfus', 'J.Elster', 'J.Evans', 'H.Geffner', 'R.Dechter', 'H.Geffner', 'J.Y', 'H.Geffner', 'M.Genesereth', 'N.Love', 'B.Pell', 'G.Gigerenzer', 'G.GigerenzerandP', 'A.Gopnik', 'C.Glymour', 'D.Sobel', 'L.Schulz', 'T.Kushnir']

推荐阅读