Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

python 3.x - What is the difference between [0,1,2,3,4] and [[0],[1],[2],[3],[4]]?

I have a list of years and multiply this with a factor 2 and get the result:

years = [0,1,2,3,4] 
x = [[2*i] for i in years]
result = [[0],[2],[4],[6],[8]] 

However, I would like to divide this by the sum of the result, but I seems like it is not possible.

Therefore, what is the difference between [0,1,2,3,4] and [[0],[2],[4],[6],[8]]? And how can I change the format so it is possible to divide each number in the result list by the sum of the results?

question from:https://stackoverflow.com/questions/65903784/what-is-the-difference-between-0-1-2-3-4-and-0-1-2-3-4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[0, 1, 2, 3, 4] is a list of integers. It's a one-dimensional list and you only need one index to access its elements. For example, years[3] is the integer 3.

[[0],[2],[4],[6],[8]] is a list of lists of integers, so it's a two-dimensional list. You need two indices to access its integer elements. For example, result[3] will give you the list [6], and the zeroth index of that list will give you the integer 6. In other words, result[3][0] gives you the integer 6.

The list comprehension result = [[2*i] for i in years] is what creates the two-dimensional list because you asked it to. You said:

  • For every i in years,
    • Calculate 2 * i
    • Put that into a list [2 * i]
  • Collect all these lists of [2 * i] in a single list.

If you wanted a 1-d list, skip the brackets around [2 * i] like so: result = [2 * i for i in years]. This tells Python to:

  • For every i in years,
    • Calculate 2 * i
  • Collect all these 2 * i into a single list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...