【问题标题】:How to print tuple "RAW"如何打印元组“RAW”
【发布时间】:2020-11-22 20:54:29
【问题描述】:

我知道我的代码很乱,但我需要为分配获得所需的输出。 我对元组输出一无所知,我的意思是如何操作...... 但是我在互联网上找到的所有内容都是关于元组的,例如: ('A', 10) 带有一个键和一个值。 据我了解,我有一个包含两个值的元组。

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
raw_dat = list()
time = list()
hour = list()
dic = dict()
rdy = list()

for line in handle :
    if not line.startswith("From") : continue
    if line.startswith("From:") : continue
    raw_dat.append(line.split())

for item in raw_dat :
    item = item[5]
    time.append(item)

for data in time :
    hour.append(data[0:2])

for hr in hour:
    dic[hr] = dic.get(hr, 0) + 1
for tm in sorted(dic.items()) :
    print(tm)

我的输出 atm...

('04', 3)
('06', 1)
('07', 1)
('09', 2)
('10', 3)
('11', 6)
('14', 1)
('15', 2)
('16', 4)
('17', 2)
('18', 1)
('19', 1)

想要的输出...

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

谢谢。

【问题讨论】:

  • 您的意思是:'print(tm[0], tm[1])'?
  • 非常感谢...简短的回答和完美的解决方案。真的谢谢你。
  • print(*tm) 会这样做
  • 在这段代码中,for line in handle : if not line.startswith("From") : continue if line.startswith("From:") : continue raw_dat.append(line.split()),你认为raw_dat.append(line.split())会被执行吗?
  • @JoeFerndz 。我不知道你的意思...起初我以为这是一个诡计问题。但是我剪切(#)这行代码,整个事情都行不通。所以我想知道你的意思。它被执行,它是代码的重要部分(至少对我来说)。

标签: python python-3.x tuples


【解决方案1】:

感谢@quamrana 帮助我... 这是给出的解决方案...

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
raw_dat = list()
time = list()
hour = list()
dic = dict()

for line in handle :
    if not line.startswith("From") : continue
    if line.startswith("From:") : continue
    raw_dat.append(line.split())

for item in raw_dat :
    item = item[5]
    time.append(item)

for data in time :
    hour.append(data[0:2])

for hr in hour:
    dic[hr] = dic.get(hr, 0) + 1
for tm in sorted(dic.items()) :
    print(tm[0], tm[1])

原创:

print(tm)

解决方案(1):

print(tm[0], tm[1])

解决方案(2):

print(*tm)

【讨论】:

  • print(*tm) 怎么样?
  • @GrzegorzSkibinski 与 print(tm[0], tm[1]) 的工作方式相同。非常感谢。
  • 我知道,它只是更短更通用。如果你愿意,更多的'python-ish'
  • @GrzegorzSkibinski 没错,看起来更像我知道自己在做什么。非常感谢你。明天我会看看“*”的一般作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 2020-04-23
  • 2019-11-22
  • 2022-01-21
  • 2018-09-25
相关资源
最近更新 更多