Add value to tuple within list - python

How to add value to tuple within list
a = [[('one','1'),('two','2')],[('three','3')]]
b = [['I','II'],['III']]
I want it to turn out like
a = [[('one','1','I'),('two','2','II')],[('three','3','III')]]
I try to use append but it doesn't work
Thanks for any help.

Tuples are immutable, which means you can't change them once they've been made. See here: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences.
The only way to achieve what you want would be to either remake your list, or delete the elements and add the new versions in-place.
You could try something like this:
a = [(1, 'one'), (2, 'two'), (3, 'three')]
b = ["I", "II", "III"]
updated_a = [(*i, j) for i, j in zip(a, b)]
Where I've assumed you've typoed in your question, and that the list of numerals has this form instead.

Related

Loop inside an f-string as a value for an embed

I have a tuple with some values and I want to send them in an embed. They're inside a dictionary like this
dict = {key: [(1, 2, 3), other values here], other key: [(1, 2, 3, 4, 5), other values here]}
Now some of the tuples here are of different lengths and it triggers me if I used a loop to add an embed field since discord doesn't allow the name parameter to be false or null yet. If I use a 0 width whitespace character, there's a big space that I'd rather not have. Tried using ternary operators but it didn't work. I also can't have this
for i in range(0, len(dict) - 1): pass
since the loop would've already came to an end before I could use it to index the tuple. I also tried doing
value = f'{tuple[i] for i in range(0, len(tuple) - 1)}'
but the bot return <generator object stats.<locals>.<genexpr> at 0x0000012E94AB3200> instead of the values inside the tuple.
Edit:
Thanks to the people who answered! It now works, thanks
tuple[i] for i in range(0, len(tuple) - 1)
Is a generator expression, it doesn't produce any values unless consumed by something like a loop or list()
You can use the equivalent list-comprehension instead:
f'{[tuple[i] for i in range(0, len(tuple) - 1)]}'
Or put the generator inside a list()
f'{list(tuple[i] for i in range(0, len(tuple) - 1))}'
Because your comprehension is not wrapped in [] it is technically a generator expression () (I think this would have worked in python 2.7 though), try this:
my_tuple = (1, 2, 3, 4)
f'{[my_tuple[i] for i in range(0, len(my_tuple) - 1)]}'
Output:
[1, 2, 3]
Also, there are no tuple comprehensions in python because tuples are immutable.

Convert list to set based on duplicate of only certain values of a tuple

In general, converting a list to set is simple, as below:
a = [1,2,3,1]
set_a = set(a) # set([1, 2, 3])
Now, I want to convert a list of tuples to set, only considering the first value of tuple.
a = [(1,"a1"), (2,"b2"), (3, "c3"), (1, "d4")]
set_a = some_magic(a)
# 1) set_a = set([(1,"a1"), (2,"b2"), (3, "c3")]) or
# 2) set_a = set([(1, "d4"), (2,"b2"), (3, "c3")])
# Both (1) or (2) are acceptible outputs.
Is there a "one-line" trick I could use instead of some_magic function mentioned above?
I want to avoid making a separate list for book-keeping which of the first index of tuples are already used [which would have been the obvious answer otherwise]
try this:
set(dict(a).items())
dict(a) will turn the list into a dictionary where the keys get overwritten by each occurrence
the .items() extracts each key-value pair into a dict_items list of tuples
the set() turns it into the set you want
Note: this will give you the second example, keeping the very last unique tuple key. If you want the first one, a different approach will be needed
Using list comprehension:
a = [(1,"a1"), (2,"b2"), (3, "c3"), (1, "d4")]
seen = set()
print([x for x in a if x[0] not in seen and not seen.add(x[0])])
OUTPUT:
[(1, 'a1'), (2, 'b2'), (3, 'c3')]
EDIT:
Using a dict:
print({x[0]: x for x in a}.values())
set_a = set(
{x[0]: x for x in a}.values()
)
you can convert to a dictionary to get rid of the duplicates
set(dict(a).items())
{(1, 'd4'), (2, 'b2'), (3, 'c3')}

How can I access each element of a pair in a pair list?

I have a list called pairs.
pairs = [("a", 1), ("b", 2), ("c", 3)]
And I can access elements as:
for x in pairs:
print x
which gives output like:
('a', 1) ('b', 2) ('c', 3)
But I want to access each element in each pair, like in c++, if we use pair<string, int>
we are able to access, first element and second element by x.first, and x.second.eg.
x = make_pair("a",1)
x.first= 'a'
x.second= 1
How can I do the same in python?
Use tuple unpacking:
>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
... print a, b
...
a 1
b 2
c 3
See also: Tuple unpacking in for loops.
If you want to use names, try a namedtuple:
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]
for pair in pairs:
print("First = {}, second = {}".format(pair.first, pair.second))
A 2-tuple is a pair. You can access the first and second elements like this:
x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1
When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].
I don't think that you'll like it but I made a pair port for python :)
using it is some how similar to c++
pair = Pair
pair.make_pair(value1, value2)
or
pair = Pair(value1, value2)
here's the source code
pair_stl_for_python
You can access the members by their index in the tuple.
lst = [(1,'on'),(2,'onn'),(3,'onnn'),(4,'onnnn'),(5,'onnnnn')]
def unFld(x):
for i in x:
print(i[0],' ',i[1])
print(unFld(lst))
Output :
1 on
2 onn
3 onnn
4 onnnn
5 onnnnn

Python: Adding within lists

It may be the fact I haven't slept yet, but I can't find the solution to this problem, so I come to you all. I have a list, with a series of sub-lists, each containing two values, like so:
list = (
(2, 5),
(-1, 4),
( 7, -3)
)
I also have a variable, a similar list with two values, that is as such:
var = (0, 0)
I want to add all the x values in list, then all the y values, and then store the sums in var, so the desired value of var is:
var = (8, 6)
How could I do it? I apologize if the answer is something stupid simple, I just need to get this done before I can sleep.
sumvar = map(sum,zip(*my_list))
should do what you want i think
This sounds like a job for "reduce" to me:
reduce(lambda a,b: (a[0]+b[0],a[1]+b[1]), list)
(8,6)
you could also use another list comprehension method, (a bit more readable):
sum(a for a,b in tpl), sum(b for a,b in tpl)
(8,6)

List formation in python

I need to put 3 items in the list.
state..eg(1,2)
action...eg..west
cost....5
list=[(state,action,cost), (state,action,cost).........]
how can i make it in a form of list. For a particular state , action and cost is there. Moreover, if i need only state from the list, i should be able to extract it from the list.same thing goes for action too.
Your wording is pretty obscure. Right now you have a list of tuples (horribly named list, which robs the use of the built-in name from the rest of that scope -- please don't reuse built-in names as your own identifiers... call them alist or mylist, if you can't think of a more meaningful and helpful name!). If you want a list of lists, code:
alist = [[state, action, cost], [state, action, cost], ...]
If you want to transform the list of tuples in a list of lists,
alist = [list(t) for t in alist]
(see why you should never usurp built-in identifiers such as list?!-).
If you want to flatten the list-of-lists (or -of-tuples) into a single list,
aflatlist = [x for t in alist for x in t]
To access e.g. "just the state" (first item), say of the Nth item in the list,
justthestate = alist[N][0]
or, if you've flattened it,
justhestate = aflatlist[N*3 + 0]
(the + 0 is clearly redundant, but it's there to show you what to do for the cost, which would be at + 1, etc).
If you want a list with all states,
allstates = [t[0] for t in alist]
or
allstates = aflatlist[0::3]
I'm sure you could mean something even different from this dozen of possible interpretations of your arcane words, but I'm out of juice by now;-).
I'm not sure I understand the first part of your question ("form of a list"). You can construct the list of tuples in the form you've stated:
mylist = [(1, 'west', 5), (1, 'east', 3), (2, 'west', 6)]
# add another tuple
mylist.append((2, 'east', 7))
To extract only the states or actions (i.e. the first or second item in each tuple), you can use list comprehensions:
states = [item[0] for item in mylist]
actions = [item[1] for item in mylist]
The code you listed above is a list of tuples - which pretty much matches what you're asking for.
From the example above, list[0][0] returns the state from the first tuple, list[0][1] the action, and list[0][2] the cost.
You can extract the values with something like (state, action, cost)= list[i] too.
try this
l = [('a',1,2),('b',3,4),('a',4,6), ('a',6,8)]
state = [sl[0] for sl in l]
or for more,
state = [sl[0] for sl in l if 'a' in sl]

Categories