I have a two-dimensional list; ie a nested list, which contains integers and strings.
mylist = [[92, "james"], [88, "john"], [75, "robert"], [80, "michael"], [25, "william"], [54, "david"], [59, "richard"], [74, "charles"], [46, "joseph"], [90, "thomas"], [80, "christopher"]]
I want to a way to go through the strings only, check if they start with a particular letter; say j
, delete it and ignore the rest of the elements that don't meet this condition.
The desired result will look like this:
mylist = [[92, "ames"], [88, "ohn"], [75, "robert"], [80, "michael"], [25, "william"], [54, "david"], [59, "richard"], [74, "charles"], [46, "oseph"], [90, "thomas"], [80, "christo, her"]]
If I understand you correctly, here is a solution using list comprehension :
mylist = [[num, (name[1:] if name[0] == "j" else name)]
for num, name in mylist]
您可以使用函数lstrip()
删除前导字符:
[[i, j.lstrip('j')] for i, j in mylist]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.