devwiki:python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Next revisionBoth sides next revision
devwiki:python [2021/12/02 10:41] – [Python 3 Changes and How to Make 2.7 Code Works] yingdevwiki:python [2022/04/17 05:24] – [data operation] ying
Line 584: Line 584:
 list=[1,2,3,4,5,6] list=[1,2,3,4,5,6]
 seq=list[::-2] # [6,4,2] seq=list[::-2] # [6,4,2]
 +
 +# list to pair list
 +info = ['name','John', 'age', '17', 'address', 'abc']
 +info_pair = zip(info[::2], info[1::2])
 +# [('name', 'John'), ('age', '17'), ('address', 'abc')] 
  
 # list flatten, and remove duplicates # list flatten, and remove duplicates
Line 1744: Line 1749:
  
   * a python web server, install by <code>python -m pip install django</code>   * a python web server, install by <code>python -m pip install django</code>
 +
 +===== openpyxl=====
 +
 +  * a new excel reader, xlsx format, not old xls format, since now everyone use new excel version
 +  * read excel as dictionary (1st key, rest data) <code python>
 +    def excel2Dict(filename):
 +        # import openpyxl
 +        # max_row = sheet.max_row
 +        # max_column = sheet.max_column
 +        wb = openpyxl.load_workbook(filename=filename, read_only=True)
 +        records = []
 +        for sheet in wb.worksheets:
 +            count = 0
 +            keys = []
 +            
 +            for row in sheet.rows:
 +                temp = []
 +                for cell in row:
 +                    if count == 0:
 +                        keys.append(str(cell.value))
 +                    else:
 +                        temp.append(str(cell.value))
 +                if count > 0:
 +                    records.append( dict(zip(keys, temp)) ) # 
 +                else:
 +                    count += 1
 +        return records
 +</code>
 +  * read excel as row data wo empty cell. <code python>
 +    def excel2Data(filename):
 +        # import openpyxl
 +        wb = openpyxl.load_workbook(filename=filename, read_only=True, data_only=True)
 +        sheet_data = []
 +        for sheet in wb.worksheets:
 +            table_data = []
 +            for row in sheet.values:
 +                row_data = []
 +                for cell in row:
 +                    if cell is not None:
 +                        row_data.append(cell)
 +                if len(row_data)>0:
 +                    table_data.append(row_data)
 +            sheet_data.append(table_data)
 +        return sheet_data
 +</code>
 ====== Python by Reference or by Value ====== ====== Python by Reference or by Value ======
  
  • devwiki/python.txt
  • Last modified: 2024/03/25 06:36
  • by ying