I want to print the 5th index value of an enumerated list. In the example code below, the 5th index value is 555. I want to print only the 555 value. The code below prints all index values from 0-8. I just want to print the value at index 5, which is 555. What is the best way to do this?
num_list = [000, 111, 222, 333, 444, 555, 666, 777, 888]
for i, d in enumerate (num_list):
print(i, d)
I solved the issue. The goal was to print the value of the nth index (i.e. 5th index) of an enumerated object. Additional the value should only be printed once. I believe the problem with the code was the indented print statement. Below is the solution.
num_list = [000, 111, 222, 333, 444, 555, 666, 777, 888]
for i, d in enumerate (num_list):
x = num_list[5]
print(x)
Related
array = [[1676, 196, 159, 29, 'invoice'], [1857, 198, 108, 28, 'date:']]
width = 159+108 = 267
height = 29+28 = 57
label = invoice date:
Required solution: [1676, 196, 267, 57, 'invoice date:']
Is there any solution to concatenate string and add numbers in same list
Assuming your other lines are for your own notes/testing, and your "required solution" is a typo, you can use zip like so:
array = [[1676, 196, 159, 29, 'invoice'], [1857, 198, 108, 28, 'date:']]
res = []
for x, y in zip(array[0], array[1]): # compare values at each index
if isinstance(x, str): # check to see if x is a string
res.append(x + ' ' + y) # add a space if x is a string
else:
res.append(x + y) # add the two integers if x is not a string
print(res)
[3533, 394, 267, 57, 'invoice date:']
Note that the concatenation above will only work if you are sure that the same indices will have strings vs. integers.
I have a dictionary that have year-month combination as the key and value of it. I used OrderedDict to sort the dictionary and getting result like below. In my expected result, after "2021-1", it should be "2021-2". But "2021-10" is coming in between.
{
"2020-11": 25,
"2020-12": 861,
"2021-1": 935,
"2021-10": 1,
"2021-2": 4878,
"2021-3": 6058,
"2021-4": 3380,
"2021-5": 4017,
"2021-6": 1163,
"2021-7": 620,
"2021-8": 300,
"2021-9": 7
}
My expected result should be like below. I want the dictionary to be sorted by least date to the last date
{
"2020-11": 25,
"2020-12": 861,
"2021-1": 935,
"2021-2": 4878,
"2021-3": 6058,
"2021-4": 3380,
"2021-5": 4017,
"2021-6": 1163,
"2021-7": 620,
"2021-8": 300,
"2021-9": 7,
"2021-10": 1
}
Appreciate if you can help.
If you want to customize the way sorting is done, use sorted with parameter key:
from typing import OrderedDict
from decimal import Decimal
data = {
"2020-11": 25,
"2020-12": 861,
"2021-1": 935,
"2021-10": 1,
"2021-2": 4878,
"2021-3": 6058,
"2021-4": 3380,
"2021-5": 4017,
"2021-6": 1163,
"2021-7": 620,
"2021-8": 300,
"2021-9": 7
}
def year_plus_month(item):
key = item[0].replace("-", ".")
return Decimal(key)
data_ordered = OrderedDict(sorted(data.items(), key=year_plus_month))
print(data_ordered)
I used Decimal instead of float to avoid any wonky floating point precision.
Is it possible to remove the for loops in this function and get a speed up in the process? I have not been able to get the same results with vector methods for this function. Or is there another option?
import numpy as np
indices = np.array(
[814, 935, 1057, 3069, 3305, 3800, 4093, 4162, 4449])
within = np.array(
[193, 207, 243, 251, 273, 286, 405, 427, 696,
770, 883, 896, 1004, 2014, 2032, 2033, 2046, 2066,
2079, 2154, 2155, 2156, 2157, 2158, 2159, 2163, 2165,
2166, 2167, 2183, 2184, 2208, 2210, 2212, 2213, 2221,
2222, 2223, 2225, 2226, 2227, 2281, 2282, 2338, 2401,
2611, 2612, 2639, 2640, 2649, 2700, 2775, 2776, 2785,
3030, 3171, 3191, 3406, 3427, 3527, 3984, 3996, 3997,
4024, 4323, 4331, 4332])
def get_first_ind_after(indices, within):
"""returns array of the first index after each listed in indices
indices and within must be sorted ascending
"""
first_after_leading = []
for index in indices:
for w_ind in within:
if w_ind > index:
first_after_leading.append(w_ind)
break
# convert to np array
first_after_leading = np.array(first_after_leading).flatten()
return np.unique(first_after_leading)
It should return the next greatest number for each in the indices array if there is one.
# Output:
[ 883 1004 2014 3171 3406 3984 4323]
Here's one based on np.searchsorted -
def next_greater(indices, within):
idx = np.searchsorted(within, indices)
idxv = idx[idx<len(within)]
idxv_unq = np.unique(idxv)
return within[idxv_unq]
Alternatively, idxv_unq could be computed like so and should be more efficient -
idxv_unq = idxv[np.r_[True,idxv[:-1] != idxv[1:]]]
Try this:
[within[within>x][0] if len(within[within>x])>0 else 0 for x in indices]
As in,
In [35]: import numpy as np
...: indices = np.array([814, 935, 1057, 3069, 3305, 3800, 4093, 4162, 4449])
...:
...: within = np.array(
...: [193, 207, 243, 251, 273, 286, 405, 427, 696,
...: 770, 883, 896, 1004, 2014, 2032, 2033, 2046, 2066,
...: 2079, 2154, 2155, 2156, 2157, 2158, 2159, 2163, 2165,
...: 2166, 2167, 2183, 2184, 2208, 2210, 2212, 2213, 2221,
...: 2222, 2223, 2225, 2226, 2227, 2281, 2282, 2338, 2401,
...: 2611, 2612, 2639, 2640, 2649, 2700, 2775, 2776, 2785,
...: 3030, 3171, 3191, 3406, 3427, 3527, 3984, 3996, 3997,
...: 4024, 4323, 4331, 4332])
In [36]: [within[within>x][0] if len(within[within>x])>0 else 0 for x in indices]
Out[36]: [883, 1004, 2014, 3171, 3406, 3984, 4323, 4323, 0]
This is the pythonic approach called list comprehension it's a shortened version of a foreach loop. So if I were to expand this out:
result = []
for x in indices:
# This next line is a boolean index into the array, if returns all of the items in the array that have a value greater than x
y = within[within>x]
# At this point, y is an array of all the items which are larger than x. Since you wanted the first of these items, we'll just take the first item off of this new array, but it is possible that y is None (there are no values that match the condition), so there is a check for that
if len(y) > 0:
z = y[0]
else:
z = 0 # or None or whatever you like
# Now add this value to the array that we are building
result.append(z)
# Now result has the array
I wrote it this way, because it uses the vector operations (i.e. the boolean mask) and also leverages list comprehension, which is a much cleaner simpler way to write a foreach which returns an array.
I've got a list of dictionaries of dictionaries... Basically, it is just big piece of JSON. Here how looks like one dict from a list:
{'id': 391257, 'from_id': -1, 'owner_id': -1, 'date': 1554998414, 'marked_as_ads': 0, 'post_type': 'post', 'text': 'Весна — время обновлений. Очищаем балконы от старых лыж и API от устаревших версий: уже скоро запросы к API c версией ниже 5.0 перестанут поддерживаться.\n\nОжидаемая дата изменений: 15 мая 2019 года. \n\nПодробности в Roadmap: https://vk.com/dev/version_update_2.0', 'post_source': {'type': 'vk'}, 'comments': {'count': 91, 'can_post': 1, 'groups_can_post': True}, 'likes': {'count': 182, 'user_likes': 0, 'can_like': 1, 'can_publish': 1}, 'reposts': {'count': 10, 'user_reposted': 0}, 'views': {'count': 63997}, 'is_favorite': False}
And I want to dump each dict to frame. if I just do
data = pandas.DataFrame(list_of_dicts)
I get a frame where are only two columns: first one contains keys, and another one contains data, like this:
I tried doing it in a loop:
for i in list_of_dicts:
tmp = pandas.DataFrame().from_dict(i)
data = pandas.concat([data, tmp])
print(i)
But I face ValueError:
Traceback (most recent call last):
File "/home/keddad/PycharmProjects/vk_group_parse/Data Grabber.py", line 68, in <module>
main()
File "/home/keddad/PycharmProjects/vk_group_parse/Data Grabber.py", line 61, in main
tmp = pandas.DataFrame().from_dict(i)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/frame.py", line 1138, in from_dict
return cls(data, index=index, columns=columns, dtype=dtype)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/frame.py", line 392, in __init__
mgr = init_dict(data, index, columns, dtype=dtype)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 212, in init_dict
return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 51, in arrays_to_mgr
index = extract_index(arrays)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 320, in extract_index
raise ValueError('Mixing dicts with non-Series may lead to '
ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.
How, after this, I can get dataframe with one post (one dictionary in the list is one post) and all the data in it as columns?
I can't figure out the df exactly but I think you simply need to do a reset_index and all the data which is currently(it seems):
df.reset_index(inplace=True)
Another thing if you want the keys as columns:
df = pd.Dataframe.from_dict(orient='columns')
# or try `index` in columns if you don't get desired results
In a for loop:
l = []
for i in dict.keys:
l.append(pd.DataFrame.from_dict(dict[i], orient='columns'))
df = pd.concat(l)
Not quite sure what you are trying to do, but do you mean something like this?
You can see inside the data by just printing the dataframe. Or you can print each one by the following code.
data = pandas.DataFrame(list_of_dicts)
print(data)
for i in data.loc[:, data.columns]:
print(data[i])
This programm have to order a list of numbersbut every time i become a error can you help me to fix it? I hope somebody has an idea. I hzave also tried to us del list[(thenumber of the element or the number)]
# list = list with the none ordert number
# newlist = with the ordert numbers
# pnumbver = privious number
# add = new number for list
# numberelemente = how many numbers get in list
# length = length of list
# i = counting up for the stop
from random import randint
list = []
newlist = []
numberelemente = 10
while numberelemente > 0:
add = randint(-100, 100)
list.append(add)
numberelemente = numberelemente - 1
print(list)
pnumber=list[0]
length = len(list)
i = 0
while i < length:
for zahl in list:
if number < pnumber:
pnumber = number
list.remove(pnumber)
newlist.append(pnumber)
i = i+1
print(newlist)
but i become this error i become them every time
eenter code her>>> runfile('C:/Users/Max/Desktop/python/liste ordnen.py', wdir='C:/Users/Max/Desktop/python')
[89, 46, 68, -30, 93, 38, -73, 91, 33, -69]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Max\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Users\Max\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Max/Desktop/python/liste ordnen.py", line 29, in <module>
list.remove(vzahl)
ValueError: list.remove(x): x not in list
I never say that you added pnumber to list so it cant delete it. Don't you mean to use.
list.append(pnumber)
This is what list.remove() does
list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
-https://docs.python.org/3/tutorial/datastructures.html
Hope this helps.