简体   繁体   中英

what does x[1] mean?

import matplotlib.pyplot as plt
%matplotlib inline

plt.style.use("ggplot")
plt.figure(figsize=(10,5))

N = len(sortedAverageList)
x = np.arange(1,N+1)
y = [x[1] for x in sortedAverageList]
width = 1

labels = [x[0] for x in sortedAverageList]

What does [x[1] for x in sortedAverageList] in the coding above? What does x[1] mean?

If sortedAverageList is a sequence containing another sequence with at least 2 elements, [x[1] for x in sortedAverageList] will give you a list of the second element in each of those sequences.

Example:

sortedAverageList  = [[1,2],[5,6],[7,8]]
print ([x[1] for x in sortedAverageList] )
#prints [2,6,8]

For each of the lists [1,2] , [5,6] , [7,8] , x[1] chooses the respective second element. x[0] would choose the first and x[2] would not work because the lists only have two elements.

Note that the x in [x[1] for x in sortedAverageList] has nothing to do with the x you define in the line above. Instead it is the variable inside the for loop to which the elements of sortedAverageList are repeatedly assigned.

I would recomment to study some basic python tutorial before continuiung with more advanced tasks like plotting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM