私信  •  关注

davedwards

davedwards 最近创建的主题
davedwards 最近回复了

将列表中的每个条目作为列表项写入工作表:

import openpyxl

l = ['apple', 'carrots', 'mango']

wb = openpyxl.Workbook()
ws = wb.active

col = 'C' # Set the desired column

for n, i in enumerate(l, 1):
    ws[col+str(n)] = i

wb.save("sample.xlsx")

应按所需列生成预期输出:

output in Excel

6 年前
回复了 davedwards 创建的主题 » python 3类和子类:创建三角形和正方形

使用代码(只需少量修改)有一种方法:

class Square(Shape):
    def __init__(self, corner, area):
        Shape.__init__(self, corner = 10)
        self.__area = area
    def set_area(self):
        self.__area = area
    def get_area(self):
        return self.__area

class Triangle(Shape):
    def __init__(self, corner, height):
        Shape.__init__(self, corner = 10)
        self.__height = height
    def set_height(self):
        self.__height = height
    def get_height(self):
        return self.__height

# example triangle
t1 = Triangle(3, 50)

# example square
s1 = Square(5, 20)

# print the attributes
print('Triangle 1 height: {height} units.'.format(height=t1.get_height()))
print('Square 1 area: {area} sq. units.'.format(area=s1.get_area()))

印刷品:

Triangle 1 height: 50 units.
Square 1 area: 20 sq. units.

可能需要调整这些值以获得合理的结果。

6 年前
回复了 davedwards 创建的主题 » python:如何将csv数据转换为数组
import csv

output = []

with open('test1.csv', 'r') as f:
    content = csv.reader(f, delimiter=',')

    for line in content:
        clean_line = filter(None, line)  # remove extra spaces
        output.append([[int(i)] for i in clean_line])

>>> print output
[[[11], [10], [8], [12], [13], [11]], [[0], [1], [0], [2], [3], [0]], [[5], [15], [13], [11], [18], [18]]]  

测试结果与预期输出相符:

desired = [ [[11],[10],[8],[12],[13],[11]], 
            [[0],[1],[0],[2],[3],[0]], 
            [[5],[15],[13],[11],[18],[18]] ]

# print output == desired   # True