简体   繁体   中英

Manipulating a list of lists in python

I am still quite new to python so any help would be much appreciated.
I had two lists of tuples consisting of int, float and int, float float where the intergers are the same in both lists.
I have since merged these two lists into a list of lists using
z = List1
L = List2

z = [[r[col] for r in z] for col in range(len(z[0]))]
L = [[r[col] for r in L] for col in range(len(L[0]))]  

final_t_matrix = []
for i in (z + L):
    if i not in final_t_matrix:
        final_t_matrix.append(i)
Wind = [[r[col] for r in final_t_matrix] for col in range(len(final_t_matrix[0]))]  

I now have a list of lists which if I run a print statement provides this (output this is only a partial output).

[1, -9.820569, -27.857089, 52.5], [2, -13.876759, -28.511313, 52.5], [3, -10.505768, -27.967606, 52.5], [4, -14.367771, -28.590508, 52.5], [5, -10.250126, -27.926373, 52.5]

I now want to manipulate this data by selecting the second and third value and taking the resultant and outputting this in a list.

my code is currently this but I seem to be missing something. The statement needs to run until a none value is reached and then stop as the list can be over 500 data points long

force = [] 
i = 0
if Wind[i][3] == 30.0:
    force.append[i] = (((Wind[i][1])**2 + (Wind[i][2])**2)**0.5)
else:
    i += 1

print(force)

*I would like to keep the resultant in a list so that I can recall the resultant that corresponds to any integer.

得到一个简单的答案,当调整输出时我想要什么。

force = [(w[0], (((w[1])**2 + (w[2])**2)**0.5), w[3]) for w in Wind]   

In your code, you have square brackets enclosing your argument to force.append, ie force.append[i] in place of force.append(i).

I'm not sure if correcting this syntactic error will be enough, but it should be a step in the right direction.

Do you mean the statements need to run until it reaches the end of the list OR the statements need to run until a None value is seen in the 4th element in the sublist?

If it's the first case, then you just need to put it in a loop:

force = [] 
for i in range(len(Wind)):
  if Wind[i][3] == 30.0:
     force.append(((Wind[i][1])**2 + (Wind[i][2])**2)**0.5)
print(force)

Otherwise, you need to put it in a loop and use a break statement:

force = [] 
for i in range(len(Wind)):
   if Wind[i][3] == None:
      break
   elif Wind[i][3] == 30.0:
      force.append(((Wind[i][1])**2 + (Wind[i][2])**2)**0.5)
print(force)

Note that this will output an empty list given the sample Wind list you've provided since there is no 4th element in the sublist that is equal to 30.

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