Have a problem, i have zipped two lists. Now u see this:
[(1951, 720)]
[(1927, 107000)]
[(1952, 1914)]
[(1976, 780)]
[(1902, 4239)]
[(1919, 910)]
How can i get it on this format:
[1976, 780]
[1902, 4239]
[1919, 910]
I have made the lists like this:
mass.append((int(data[i]['mass'])))
year.append(int(str(data[p]['year'])))
UPDATE;
Still dosen't work:
My code so far are here:
import json
import itertools
from pprint import pprint
json_data = open('meteors.json')
data = json.load(json_data)
year = []
for p in range(0, 1180):
if data[p]['year'] != "":
year.append(str(data[p]['year']))
mass = []
for i in range(0, 1180):
if data[i]['mass'] != 0:
mass.append((str(data[i]['mass'])))
#mass.sort()
if year > '1900':
print year
year_and_mass = zip(year, mass)
print [(year_and_mass)]
#for v in year_and_mass:
#print map(year_and_mass, v)
#for item in itertools.izip(year, mass):
#for item in zip(year, mass):
#print [item]
#for v in item:
#print map(item, v)
#for v in item:
#
#print map(item, v)
so i still get the same format as in the top as i wrote., also as u can see i tried map command.
Having read both this and your earlier question, it seems to me you actually want to get to a text representation of your data - where your data is originally in a list of tuples.
This is best done by iterating over the list and printing out in the format you actually need. If you started out with
myData = [[(1,2)],[(3,4)],[(4,5)]]
Then a simple print myData gives you
[[(1, 2)], [(3, 4)], [(4, 5)]]
Trying to iterate, you might do
for v in myData:
print v
Which results in:
[(1, 2)]
[(3, 4)]
[(4, 5)]
which is what you were showing. Now, if instead you did
for v in myData:
print map(list, v)
You get
[[1, 2]]
[[3, 4]]
[[4, 5]]
Almost what you want, but one too many square brackets. And so you find your solution:
for v in myData:
print map(list, v)[0]
with the result:
[1, 2]
[3, 4]
[4, 5]
I believe this takes you from "what you have" to "what you need". I admit that without the comments from #truefalse I would not have done this - but it was really only after reading the other question you posed that I put this together.
For future reference - it is better to edit / improve your question, rather than ask a new one...
Related
I want remove list b from list a without changing id of list a I tried below method:
for i in b:
a.remove(i)
Is there any better ways?
Something like the below?
a = [1, 2, 3]
b = [4, 5, 3]
for i in b:
try:
a.remove(i)
except ValueError:
pass
print a
Alternatively:
a = [i for i in a if i not in b]
print a
If I have an input like this (1, 2, 3, 4, 5, 6)
The output has to be ... [[1, 2], [3, 4], [5, 6]].
I know how to deal with if it's one element but not two.
x=[]
for number in numbers:
x.append([number])
I'll appreciate your any help!
Something like this would work:
out = []
lst = (1,2,3,4,5,6,7,8,9,10)
for x in range(len(lst)):
if x % 2 == 0:
out.append([lst[x], lst[x+1]])
else:
continue
To use this, just set lst equal to whatever list of numbers you want. The final product is stored in out.
There is a shorter way of doing what you want:
result = []
L = (1,2,3,4,5,6,7,8,9,10)
result = [[L[i], L[i + 1]] for i in range(0, len(L) - 1, 2)]
print(result)
You can use something like this. This solution also works for list of odd length
def func(lst):
res = []
# Go through every 2nd value | 0, 2, 4, ...
for i in range(0, len(lst), 2):
# Append a slice of the list, + 2 to include the next value
res.append(lst[i : i + 2])
return res
# Output
>>> lst = [1, 2, 3, 4, 5, 6]
>>> func(lst)
[[1, 2], [3, 4], [5, 6]]
>>> lst2 = [1, 2, 3, 4, 5, 6, 7]
>>> func(lst2)
[[1, 2], [3, 4], [5, 6], [7]]
List comprehension solution
def func(lst):
return [lst[i:i+2] for i in range(0, len(lst), 2)]
Slicing is better in this case as you don't have to account for IndexError allowing it to work for odd length as well.
If you want you can also add another parameter to let you specify the desired number of inner elements.
def func(lst, size = 2): # default of 2 it none specified
return [lst[i:i+size] for i in range(0, len(lst), size)]
There's a few hurdles in this problem. You want to iterate through the list without going past the end of the list and you need to deal with the case that list has an odd length. Here's one solution that works:
def foo(lst):
result = [[x,y] for [x,y] in zip(lst[0::2], lst[1::2])]
return result
In case this seems convoluted, let's break the code down.
Index slicing:
lst[0::2] iterates through lst by starting at the 0th element and proceeds in increments of 2. Similarly lst[1::2] iterates through starting at the 1st element (colloquially the second element) and continues in increments of 2.
Example:
>>> lst = (1,2,3,4,5,6,7)
>>> print(lst[0::2])
(1,3,5,7)
>>> print(lst[1::2])
(2,4,6)
zip: zip() takes two lists (or any iterable object for that matter) and returns a list containing tuples. Example:
>>> lst1 = (10,20,30, 40)
>>> lst2 = (15,25,35)
>>> prit(zip(lst1, lst2))
[(10,15), (20,25), (30,35)]
Notice that zip(lst1, lst2) has the nice property that if one of it's arguments is longer than the other, zip() stops zipping whenever the shortest iterable is out of items.
List comprehension: python allows iteration quite generally. Consider the statement:
>>> [[x,y] for [x,y] in zip(lst1,lst2)]
The interior bit "for [x,y] in zip(lst1,lst2)" says "iterate through all pairs of values in zip, and give their values to x and y". In the rest of the statement
"[[x,y] for [x,y] ...]", it says "for each set of values x and y takes on, make a list [x,y] to be stored in a larger list". Once this statement executes, you have a list of lists, where the interior lists are all possible pairs for zip(lst1,lst2)
Very Clear solution:
l = (1, 2, 3, 4, 5, 6)
l = iter(l)
w = []
for i in l:
sub = []
sub.append(i)
sub.append(next(l))
w.append(sub)
print w
I have an array [1,2,3,4,5,6,1,2,3,4] and I would like to return 5, 6.
If I use set(my_array) I get 1,2,3,4,5,6. Is there a pythonic way to do this. Thanks.
Any help is much appreciated.
#List of data which has every item repeated except for 5 and 6
lst= [1,2,3,4,5,6,1,2,3,4]
#This list comprehension prints a value in the list if the value only occurs once.
print [x for x in lst if lst.count(x)==1]
#Output
[5, 6]
You can use the appropriately named filter method:
>>> i = [1,2,3,4,5,6,1,2,3,4]
>>> filter(lambda x: i.count(x) == 1, i)
[5, 6]
I got the following problem:
I'm writing a script for Ensight (a program for visualizing CFD computations) in python.
The program Ensight gives me a list for the time values like:
print ensight.query(ensight.TIMEVALS)['timevalues']
[[0, 0.0], [1, 9.99e-07], [2, 1.99e-06], [3, 0.0003],etc.]
Where the first value in every list is the timestep and the second value the actual time at this timestep. Now I want to ask somehow for timestep '2' and want to know the corresponding second value of the list. Therefore if I could just find the index of the timestep I could easily have the corresponding time value.
EDIT\\
It solved it now like this:
time_values = ensight.query(ensight.TIMEVALS)['timevalues']
for start,sublist in enumerate(time_values):
if step_start in sublist:
index_begin = start
for end,sublist in enumerate(time_values):
if step_stop in sublist:
index_end = end
Maybe this is what you want?
print ensight.query(ensight.TIMEVALS)['timevalues'][1][1]
That should print the 9.99e-07 as it is the second value in the second list included in your main list.
I'm just wondering why you have 3 opening and just 2 closing brackets. Is this a typo?
[[ [..].. ]
If you have a list like myList = [[0, 0.0], [1, 9.99e-07], [2, 1.99e-06], [3, 0.0003],etc.]
you can access the first nested list with myList[0] resulting in [0, 0.0]
To access the second value in that list you can use myList[0][1]
Set n to the required timestep value
>>> n=2
>>> print [list[1] for list in ensight.query(ensight.TIMEVALS)['timevalues'] if list[0]=n ]
this can also be extended in your case
>>> from=2
>>> to=100
>>> print [list[1] for list in ensight.query(ensight.TIMEVALS)['timevalues'] if (list[0]>from && list[0]<to) ]
>>> l = ensight.query(ensight.TIMEVALS)['timevalues']
>>> print l
[[0, 0.0], [1, 9.99e-07], [2, 1.99e-06], [3, 0.0003]]
>>> _d = {int(ele[0]): ele[1] for ele in l}
>>> print _d[2]
1.99e-o6
I'm trying to understand how comprehensions work.
I would like to loop through two lists, and compare each to find differences.
If one/or-more word(s) is different, I would like to print this word(s).
I'd like this all in one nice line of code, which is why I'm interested in comprehensions.
Doing it in "one nice line of code" is code golf, and misguided. Make it readable instead.
for a, b in zip(list1, list2):
if a != b:
print(a, "is different from", b)
This is not different in any significant way from this:
[print(a, "is different from", b) for a, b in zip(list1, list2) if a!=b]
Except that the expanded version easier to read and understand than the comprehension.
Like kriegar suggested using sets is probably the easiest solution. If you absolutely need to use list comprehension, I'd use something like this:
list_1 = [1, 2, 3, 4, 5, 6]
list_2 = [1, 2, 3, 0, 5, 6]
# Print all items from list_1 that are not in list_2 ()
print(*[item for item in list_1 if item not in list_2], sep='\n')
# Print all items from list_1 that differ from the item at the same index in list_2
print(*[x for x, y in zip(list_1, list_2) if x != y], sep='\n')
# Print all items from list_2 that differ from the item at the same index in list_1
print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n')
If you want to compare two lists for differences, I think you want to use a set.
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
example:
>>> L1 = ['a', 'b', 'c', 'd']
>>> L2 = ['b', 'c', 'd', 'e']
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> difference = list(S1.symmetric_difference(S2))
>>> print difference
['a', 'e']
>>>
one-line form?
>>> print list(set(L1).symmetric_difference(set(L2)))
['a', 'e']
>>>
if you really want to use a list comprehension:
>>> [word for word in L1 if word not in L2] + [word for word in L2 if word not in L1]
['a', 'e']
much less efficient as the size of the lists grow.