python - Concatenating two strings in a list of lists -
the title bit misleading i'm not quite clever enough come appropriate header describes i'm trying accomplish, apologize that. can compensate description below.
i'm working on exercise book requires bit of cleanup before can perform other operations. have list of lists in elements in some, not all, of these lists require update through concatenation (or perhaps other, more efficient, means if people suggest them). better explain, here slice list of lists:
[['e726fb69de83a3ec', 'general_mobile', 'android', 'unknown', '0'], ['1b8978f618d59eef', 'general_mobile', 'ios', 'unknown', '0'], ['8ee82ed6c2c5af59', 'general_desktop', 'windows', 'xp', 'male', '29'], ['d0fff09ca1829e65', 'general_mobile', 'android', 'female', '48'], ['3126deccaae39ea1', 'general_desktop', 'windows', 'xp', 'male', '24'], ['6778d882a1f59b5b', 'general_mobile', 'ios', 'female', '25']]
the elements in each list correspond userid, device, os, sex , provinceid, respectively. if take @ third , fifth lists, dilemma arises--you'll notice 'windows' , 'xp' separate strings should instead single string, i.e., 'windows xp', these 2 strings appear in respective lists amongst others as:
['8ee82ed6c2c5af59', 'general_desktop', 'windows xp', 'male', '29'] ['3126deccaae39ea1', 'general_desktop', 'windows xp', 'male', '24']
the remaining lists above absolved problem, there no need modify them.
so, i've tried develop reasonable means can join 2 strings in lists have such separation (i have other lists not shown in sample above displayed similarly, e.g., 'windows' '7' instead of 'windows 7'), i've yet so. there 'clean' way of doing or have resort creating loop removes these strings , inserts concatenation of two?
you use simple list comprehension:
>>> data = [['e726fb69de83a3ec', 'general_mobile', 'android', 'unknown', '0'], ['1b8978f618d59eef', 'general_mobile', 'ios', 'unknown', '0'], ['8ee82ed6c2c5af59', 'general_desktop', 'windows', 'xp', 'male', '29'], ['d0fff09ca1829e65', 'general_mobile', 'android', 'female', '48'], ['3126deccaae39ea1', 'general_desktop', 'windows', 'xp', 'male', '24'], ['6778d882a1f59b5b', 'general_mobile', 'ios', 'female', '25']]
and then:
>>> [item if len(item) == 5 else item[:2] + [' '.join(item[2:4])] + item[4:] item in data] [['e726fb69de83a3ec', 'general_mobile', 'android', 'unknown', '0'], ['1b8978f618d59eef', 'general_mobile', 'ios', 'unknown', '0'], ['8ee82ed6c2c5af59', 'general_desktop', 'windows xp', 'male', '29'], ['d0fff09ca1829e65', 'general_mobile', 'android', 'female', '48'], ['3126deccaae39ea1', 'general_desktop', 'windows xp', 'male', '24'], ['6778d882a1f59b5b', 'general_mobile', 'ios', 'female', '25']]
Comments
Post a Comment