私信  •  关注

Olvin Roght

Olvin Roght 最近创建的主题
Olvin Roght 最近回复了
6 年前
回复了 Olvin Roght 创建的主题 » python中如何在负数前加括号

您可以定义函数,如果数字为负数,则该函数将添加括号,并使用它代替 str() :

def fmt_num(x):
    return str(x) if x >= 0 else "({})".format(x)

...

print("The quadratic equation is : " + fmt_num(a) + "x2+" + fmt_num(b) + "x+" + fmt_num(c))
6 年前
回复了 Olvin Roght 创建的主题 » 如何使用python将嵌套的JSON数据转换为CSV?

这显然不是最好的例子,但我要努力优化它。

import csv


def json_to_csv(obj, res):
    for k, v in obj.items():
        if isinstance(v, dict):
            res.append(k)
            json_to_csv(v, res)
        elif isinstance(v, list):
            res.append(k)
            for el in v:
                json_to_csv(el, res)
        else:
            res.append(v)


obj = {
  "Result": {
    "Example 1": {
      "Type1": [
        {
          "Owner": "Name1 Example",
          "Description": "Description1 Example",
          "Email": "example1_email@email.com",
          "Phone": "(123) 456-7890"
        }
      ]
    },
    "Example 2": {
      "Type1": [
        {
          "Owner": "Name2 Example",
          "Description": "Description2 Example",
          "Email": "example2_email@email.com",
          "Phone": "(111) 222-3333"
        }
      ]
    }
  }
}

with open("out.csv", "w+") as f:
    writer = csv.writer(f)
    writer.writerow(["Address","Type","Owner","Description","Email","Phone"])
    for k, v in obj["Result"].items():
        row = [k]
        json_to_csv(v, row)
        writer.writerow(row)
6 年前
回复了 Olvin Roght 创建的主题 » 用N行输入N从Python打印直角三角形

检查文档 range() step 参数,它允许传递每个步骤的增量。所以,在代码中使用它的正确方法是:

for row in range(lastNumber):
    for column in range(lastNumber, lastNumber - row - 1, -1):
        print(column, end=" ")
    print("")

还有一对衬垫,它们是一样的:

print("\n".join(" ".join(map(str, range(5, 4 - n, -1))) for n in range(5)))
print(*(" ".join(map(str, range(5, 4 - n, -1))) for n in range(5)), sep="\n")