0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonのみで2次元配列の転置、型変換を行う方法[備忘録]

Last updated at Posted at 2020-11-24

やりたいこと

pythonの二次元配列を転置してさらにint をstrに変換する
pandas やnd.array は使わないで行いたい

example.txt
[
[5, 0, 1, 1], 
[1, 0, 1, 5], 
[0, 1, 6, 0], 
[0, 4, 3, 0], 
[5, 2, 0, 0], 
[5, 0, 1, 1], 
[0, 6, 0, 1], 
[0, 1, 0, 6]
]

=>

[
['5', '1', '0', '0', '5', '5', '0', '0'], 
['0', '0', '1', '4', '2', '0', '6', '1'],
 ['1', '1', '6', '3', '0', '1', '0', '0'], 
['1', '5', '0', '0', '0', '1', '1', '6']
]

code

hoge.py
cnt_ACGT_t = [list(map(str,i)) for i in zip(*cnt_ACGT)]

転置

複数のイテラブルを受け取り、同じ場所の要素でまとめたイテレータを返す組み込み関数であるzipを用いる

zip(*cnt_ACGT)

でcnt_ACGTのリストを転置したものがイテレータオブジェクトに変換された

全要素のintからstrの変換

zip(*cnt_ACGT)はイテレータなので、そのままリスト内包表記を使って各要素をstrに変換する
1行ごとのリストにたいしてmap でstrに変換する

参考

https://note.nkmk.me/python-list-transpose/ おなじみnkmkさんのブログを参考にしました

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?