【问题标题】:Replace all occurrences of the same key of an array with a character, skip the first replacement [closed]用字符替换数组中所有出现的相同键,跳过第一次替换[关闭]
【发布时间】:2016-01-14 18:41:17
【问题描述】:

我尝试了很多方法来解决这个问题,但因为我是 Python 新手,所以无法用几行代码完成。我想知道是否有人对以下问题有一个优雅的解决方案。

我有这样的原始台词:

A: D

A: E

A: C

G: H
F: I

F: J

B: A

B: K

B: L

D: M

D: N

D: O

E: P

E: Q

C: R

C: S

C: T

如何使用 Python 将它们变成这种形式?

A: D; E; C

G: H

F: I; J

B: A; G; L

D: M; N; O

E: P; Q

C: R; S; T

也就是说,将“:”前具有相同字符的条目组合起来,并用“;”分隔每个元素

【问题讨论】:

  • 您是否已经尝试在 Python 中实现这一点,如果是,您在为什么呢?请记住,SO 不是代码编写服务。此外,您可能希望看到stackoverflow.com/help/mcve 来编辑您的帖子,以便回答者更易于管理。

标签: python regex text


【解决方案1】:

存储在字典中,然后打印:

lines = """foo: bar
foo: baz
a: b"""

result = {}
for line in lines.split("\n"):
    (word, sentence) = line.split(":",1)
    word = word.strip()
    if word not in result:
        result[word] = []
    result[word].append(sentence.strip())

for word in result.keys():
    print word + ": " + "; ".join(result[word])

【讨论】:

    【解决方案2】:

    使用字典并在 ':' 上分割每一行。

    读取每一行,Key 是 pre ':' split,value 是 post ':' split。为第一个值与附加值添加一些逻辑

    my_dict = dict()
    
    with open('file.txt') as f:
        for line in f:
            key,value = line.split(':')
            if my_dict[key] is None:
                my_dict[key] = value
            else:
                my_dict[key] += '; {0}'.format(value)
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2022-10-07
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 2011-08-25
      相关资源
      最近更新 更多