问题
I'm completely new at Python and have an assignment coming up. The professor has asked that we look at examples of users coding Pascal's Triangle in Python for something that will be 'similar'.
I managed to find several ways to code it but I found several people using some code that I don't understand.
Essentially, I'm looking to find out what it means (or does) when you see a list or variable that has two square brackets side by side. Example code:
pascalsTriangle = [[1]]
rows = int(input("Number of rows:"))
print(pascalsTriangle[0])
for i in range(1,rows+1):
pascalsTriangle.append([1])
for j in range(len(pascalsTriangle[i-1])-1):
pascalsTriangle[i].append(pascalsTriangle[i-1][j]+ pascalsTriangle[i-1][j+1])
pascalsTriangle[i].append(1)
print(pascalsTriangle[i])
You'll see that line 7 has this:
pascalsTriangle[i].append(pascalsTriangle[i-1][j]+pascalsTriangle[i-1][j+1])
I know that square brackets are lists. I know that square brackets within square brackets are lists within/of lists. Can anyone describe what a square bracket next to a square bracket is doing?
回答1:
If you have a list
l = ["foo", "bar", "buz"]
Then l[0] is "foo", l[1] is "bar", l[2] is buz.
Similarly you could have a list in it instead of strings.
l = [ [1,2,3], "bar", "buz"]
Now l[0] is [1,2,3].
What if you want to access the second item in that list of numbers? You could say:
l[0][1]
l[0] first gets you the list, then [1] picks out the second number in it. That's why you have "square bracket next to square bracket".
回答2:
Square brackets are used to define lists, but also to get things from lists.
When you have a list of lists and want something from an inner list, you need to get that inner list (using brackets) and then get the desired thing inside (using brackets again).
lol = [[1, 2, 3], [4, 5, 6]]
lol[1]
# [4, 5, 6]
lol[1][0]
# 4
来源:https://stackoverflow.com/questions/41083869/double-square-brackets-side-by-side-in-python