0

I have an array like this.

    [['Bob\n', 0], ['Joe\n', 0], ['Bill', 0], ['Steve', 0], ['Judy', 0]]

and I would like to change one of the zeros to 1. How would I direct a .append to the 0 after Joe for example. I am new to python and can not currently use numPy unfortunately. Also how do you get rid of that stupid \n at the end of a few of the lists?

1
  • 1
    change and append have different meaning. You want to change the value or append the new value? Commented Dec 16, 2016 at 19:49

3 Answers 3

2

You can use list indexes:

>>> mylist = [['Bob\n', 0], ['Joe\n', 0], ['Bill', 0], ['Steve', 0], ['Judy', 0]]
>>> mylist[1][1] = 'new_value'
>>> mylist
[['Bob\n', 0], ['Joe\n', 'new_value'], ['Bill', 0], ['Steve', 0], ['Judy', 0]]

In mylist, in 2nd element (1), in 2nd element of sublist, I set 'new_value'

And for \n, you can use str.strip:

>>> mylist = [['Bob\n', 0], ['Joe\n', 0], ['Bill', 0], ['Steve', 0], ['Judy', 0]]
>>> mylist = [[i.strip(), j] for i, j in mylist]
>>> mylist
[['Bob', 0], ['Joe', 0], ['Bill', 0], ['Steve', 0], ['Judy', 0]]

Use a list-comprehension and apply strip to 1st element of all sublists.

Sign up to request clarification or add additional context in comments.

1 Comment

Change the zero to one, not append a new zero. OP is not very clear tho.
1

it wont let me comment, but I wanted to add to zulu's answers:

>>>mylist = [['Bob\n', 0], ['Joe\n', 0], ['Bill', 0], ['Steve', 0], ['Judy', 0]]
#so far so good, but change mylist[1][0] to mylist[1][1]
>>>mylist[1][1] = 1
>>>mylist
[['Bob\n', 0], ['Joe\n', 1], ['Bill', 0], ['Steve', 0], ['Judy', 0]]

you can access an element of a list using [int] so, mylist[1] is the element of mylist. mylist[1] also happens to be a list. lets say this (assume I didnt change the value yet):

>>>inside_list = mylist[1]
>>>inside_list
['Joe\n', 0]

now I can access this inside list. 0 is the number i want to replace, at index 1, so we can do this:

>>>inside_list[1] = 1
>>>inside_list
['Joe\n', 1]

as a side note, since 0 is an integer, you can also do this:

>>>inside_list[1]+=1
>>>inside_list
['Joe\n', 1]

Comments

0

>>>input = [['Bob\n', 0], ['Joe\n', 0], ['Bill', 0], ['Steve', 0], ['Judy', 0]] >>>output = map(lambda x: [x[0].rstrip(), x[1] or 1], input)

>>>output

>>>[['Bob', 1], ['Joe', 1], ['Bill', 1], ['Steve', 1], ['Judy', 1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.