【问题标题】:Need help to produce output for below input using python list [closed]需要帮助使用 python list 为以下输入生成输出[关闭]
【发布时间】:2018-10-03 08:04:44
【问题描述】:

输入数据如下:

0:70 1:60 2:66 3:62 4:72 5:82 6:83 7:86 8:95 9:96 10:98 11:98 12:96 13:94 14:66 15:62 16:60 17:66 18:67 19:67 20:64 21:66 22:66 23:69

使用python输出如下

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

70 60 66 62 72 82 83 86 95 96 98 98 96 94 66 62 60 66 67 67 64 66 66 69

【问题讨论】:

  • 输入的是字符串吗?
  • 你到底在问什么?
  • 嗨,欢迎来到堆栈溢出。提供stackoverflow.com/help/mcve 可能会增加您获得满意答案的机会。
  • 你试过什么?请显示您尝试解决问题的代码。 SO 用户不适用于代码编写服务。
  • 我们停止猜测并关闭问题,直到 OP 提出minimal reproducible example 并尝试一下如何?

标签: python python-2.7


【解决方案1】:

代码(更新):

import re

l = "0: 70 1: 60 2: 66 3: 62 4: 72 5: 82 6: 83 7: 86 8: 95 9: 96 10: 98 11: 98 12: 96 13: 94 14: 66 15: 62 16: 60 17: 66 18: 67 19: 67 20: 64 21: 66 22: 66 23: 69"

l = re.split("\s(?=\d+:)", l)

a = []
b = []
for x in l:
    a.append(x.split(": ")[0])
    b.append(x.split(": ")[1])

a = ["<td>" + x + "</td>" for x in a]
b = ["<td>" + x + "</td>" for x in b]

print("<table><tr>" + "".join(a) + "</tr><tr>" + "".join(b) + "</tr></table>")

【讨论】:

  • 收到如下错误 Traceback(最近一次调用最后一次):文件“.\SRX-Util-report.py”,第 123 行,在 b.append(x.split( ": ")[1]) IndexError: 列表索引超出范围
  • @GirishB 代码已更新。
  • 非常感谢您的帮助...它对我有用 –
【解决方案2】:

我假设您的输入数据结构是 python dict(关联数组)。您正在尝试打印此dict 中的键和值列表。下面的代码 sn -p 将打印 keysvalues

input = {0: 70, 1: 60, 2: 66, 3: 62, 4: 72, 5: 82, 6: 83, 7: 86, 8: 95, 9: 96, 10: 98, 11: 98, 12: 96, 13: 94, 14: 66, 15: 62, 16: 60, 17: 66, 18: 67, 19: 67, 20: 64, 21: 66, 22: 66, 23: 69}
# Below is the output with keys, values
print(input.keys())
print(input.values())

【讨论】:

  • 我在 HTML 表格中需要它
  • Python dicts(尤其是 Py2.7)不要保持秩序!你可能被误导了,因为你使用的 Py3.x 版本可能确实记得插入顺序,但它并不总是如此!
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 2016-10-16
  • 2022-07-20
  • 2020-09-13
相关资源
最近更新 更多