1

I have searched and found nothing that suits my needs.

I have three for loops that each has an if conditions inside it. Here is the code:

for friend in friends:
    columns = friend.split("\n")
    if len(columns) == 4:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)""", (columns))

for friend in friends:
    columns = friend.split("\n")
    if len(columns) == 3:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))

for friend in friends:
    columns = friend.split("\n")
    if len(columns) == 2:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))

Is there a more efficient way of doing this? I was thinking of the and operator like so:

 for friend in friends:
    columns = friend.split("\n")
    if len(columns) == 4:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)""", (columns))
and
        if len(columns) == 3:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))
and
        if len(columns) == 2:
        c.execute("""INSERT INTO `fb_friends`(`name`, `already_friends`) VALUES (?, ?)""", (columns))

Can any one suggest the best or most efficient way of doing this as apposed to iterating three times over the same list?

2
  • 1
    You could avoid if statements and pad columns to size 4 instead: columns + [None]*(4-len(columns)) Commented Nov 12, 2016 at 16:33
  • 1
    I find your use of (columns) extremely misleading. It does nothing (you can replace (columns) with columns and nothing will change), but it is similar to (columns, ) (note the final comma!) which create a 1-element tuple... Commented Nov 12, 2016 at 16:52

4 Answers 4

3

You are looking for if/elif/else:

if len(smth) == 5:
    # do this
elif len(smth) == 6:
    # do that
else:
    # do something else
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ForceBru exactly what I needed.
2

Full code here:

for friend in friends:
    columns = friend.split("\n")
    if len(columns) == 4:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)""", (columns))
    elif len(columns) == 3:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))
    elif len(columns) == 2:
        c.execute("""INSERT INTO `fb_friends`(`name`, `already_friends`) VALUES (?, ?)""", (columns))

1 Comment

Thanks MaRZoCHi exactly what I needed. I chose your answer as the correct one as it uses my original code in its example
1
reqtemplate = "INSERT INTO `fb_friends`(%s) VALUES (%s)"
fields = ['`name`', '`no_of_mutual_friends`', '`no_of_new_posts`', '`already_friends`']
for friend in friends:
    columns = friend.split("\n")
    lenc = len(columns)
    c.execute(reqtemplate % (",".join(fields[:lenc]), ",".join("?" * lenc)), (columns))

4 Comments

I'm struggling to understand this code, but if I'm correct in my logic the final line here will cause the length of fields to be equal length to lenc? but I needed to cut out 'no_of_mutual_friends' & 'no_of_new_posts' not 'no_of_new_posts' & 'already_friends' when len(columns) == 2. I always have name and already_friends, but don't always have the others
sofields[:lenc]
so fields[:lenc] do this fields[:2] is from 0 included to 2 excluded: 'name', 'no_of_mutual_friends' If you always have 'name' and 'already_friends' you have to change the order in fields list
if already friends is always in the end, you can use other construction: fields[ : lenc-1] + fields[-1:]
1

On top of ForceBru answer which is the cleanest one... here is an alternative one for fun.

d = {2: """INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""",
     3: """INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""",
     4: """INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)"""}
for friend in friends:
    columns = friend.split("\n")
    try:
        c.execute(d[len(columns)], (columns))
    except KeyError:
        print("you sure about this columns length which was:", len(columns))

2 Comments

Just to point out that ForceBru and MaRZoCHi answers are basically the same with the exception that MaRZoCHi was more specific to my code, e.g. ForceBru used the numbers 5 & 6 which will never be a length of any of the columns.. and your error handler is a cool addition but is not needed if the code does not allow for any errors :/ but +1 for the use of a dict
Marzochi's answer was not there when I posted :) so wasn't comparing their answers to each other but Forcebru's to mine :). And thanks, if you don't need protection of try/except you can always remove it :).

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.