2020年10月13日 星期二

[ Python 常見問題 ] Explicitly select items from a list or tuple

 Source From Here

Question
I have the following Python list (can also be a tuple):
  1. myList = ['foo''bar''baz''quux']  
How do I explicitly pick out items whose indices have no specific patterns? For example, I want to select [0,2,3]. Or from a very big list of 1000 items, I want to select [87, 342, 217, 998, 500]. Is there some Python syntax that does that? Something that looks like:
>>> myBigList[87, 342, 217, 998, 500]

HowTo
We can leverage list comprehension feature to accomplish it:
>>> my_big_list = list(range(1000))
>>> my_selected_list = [my_big_list[i] for i in [87, 342, 217, 998, 500]]
>>> my_selected_list
[87, 342, 217, 998, 500]

I compared the answers with python 3.8:


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...