【问题标题】:How do I split on the second " , " [duplicate]如何拆分第二个“,” [重复]
【发布时间】:2021-09-20 10:12:59
【问题描述】:

我想在第二个分开,

file = open()
dictionary = {}
for linje in filen:
    bites = linje. split()
    month = bites[0]
    temp = bites[0]
    dictionary[month] = temp
print(dictionary)

文件如下所示:

Jan,1,2.7
Jan,2,2.8
Jan,3,0.7
Jan,4,1.8
Jan,5,1.2
...... each day every day of the year.

如果我写split(","),输出在我的字典中变成这样:

{Jan : Jan}.

如果我不拆分它会变成这样:

{Jan,1,2.7 : Jan,1,2.7}

我希望它是这样的:

{Jan,1: 2.7}

【问题讨论】:

  • date=','.join([bites[0], bites[1]]); temp = bites[2]; dictionary[date] = temp

标签: python dictionary split


【解决方案1】:

您可以从右侧拆分并指定要拆分的数量:

with open('file_name') as filen:
    dictionary = {}
    for linje in filen:
        month, value = linje.rsplit(',', maxsplit=1)
        dictionary[month] = value
    print(dictionary)

旁注:我建议以上下文管理器的身份打开文件,即使用with 语句。

【讨论】:

  • @victorialangoe rpartition 比 rsplit 快,看到这个链接有 200 万句:stackoverflow.com/questions/69210306/…
  • @user1740577 你会花更多时间写“rpartition”而不是节省 365 行代码
  • 我很难理解你 ;)
  • @YevhenKuzmovych 从技术上讲,linje.rpartition(',') 是 21 个字符,而 linje.rsplit(',', maxsplit=1) 是 29 个字符 ;-)
【解决方案2】:

我会选择上面的“rsplit”解决方案,但这里有一个正常拆分的解决方案:

file = open()
dictionary = {}
for linje in filen:
    digit,temp= linje[4:].split(',')
    month = linje[:4] # Months are represented by 3 chars. (4, including the comma)
    dictionary[month+digit] = temp #concat the digit to the month
print(dictionary)

【讨论】:

  • 如果您假设列具有固定宽度,则根本不应该使用拆分:dictionary = {linje[:5]: linje[6:] for linje in filen}
  • @Stef 当您到达十月 (10) 至十二月 (12) 时,您需要更改切片的长度
【解决方案3】:

使用rsplit 拆分一次。

>>> part1, part2 = 'Jan,3,0.7'.rsplit(',', maxsplit=1)
>>> part1
'Jan,3'
>>> part2
'0.7'

【讨论】:

    【解决方案4】:
    file = '''Jan,1,2.7
    Jan,2,2.8
    Jan,3,0.7
    Jan,4,1.8
    Jan,5,1.2'''
    file = file.split('\n')
    
    keys = []
    keysdata = []
    for i in range(len(file)):
        files = file[i].split(',')
        keys.append(f'{files[0]}, {files[1]}')
        keysdata.append(float(files[2]))
    dictionary = dict(zip(keys, keysdata))
    
    print(dictionary)
    

    输出:

    {'Jan, 1': 2.7, 'Jan, 2': 2.8, 'Jan, 3': 0.7, 'Jan, 4': 1.8, 'Jan, 5': 1.2}
    

    【讨论】:

    • 我建议改用keys.append((files[0], int(files[1]))),将密钥存储为实际的python对(月、日)。
    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2020-01-08
    • 2011-04-11
    相关资源
    最近更新 更多