如何使用python遍历由':'分隔的思想字符串


  • 我有字符串s="1:a:2,2:b:4:3:c:4:4:d:1";

  • 1:a:2第一个是员工id,第二个是人名,第三个是经理id

  • 我的输出是

a is report to b
b is report to d
c is report to d
d is report to a
l = []
for each in s.split(','):
for each_ite in each:
l.append(each_ite)
for each in l:
#find the first element
#traverse to 3rd element

通过{emp_id: (emp_name, man_id) ...}:的映射

s = "1:a:2,2:b:4,3:c:4,4:d:1"
d = dict([((data := el.split(':'))[0], data[1:]) for el in s.split(',')])
for e_id, (e_name, m_id) in d.items():
print(f"{e_name} is reported to {d[m_id][0]}")

a is reported to b
b is reported to d
c is reported to d
d is reported to a

让我们根据您的数据创建一个字典列表。您的主要问题是没有拆分:上的每个条目。

s = "1:a:2,2:b:4,3:c:4,4:d:1"
data = [
{'emp_id': info[0], 'name': info[1], 'mgr_id': info[2]}
for line in s.split(',')
# splitting the line on ':' into a list of substrings
# and storing in a tuple of one element lets us essentially
# assign the name 'info` to this list and use it in creating 
# the dictionary.
for info in (line.split(':'),)
]
# [{'emp_id': '1', 'name': 'a', 'mgr_id': '2'}, 
#  {'emp_id': '2', 'name': 'b', 'mgr_id': '4'}, 
#  {'emp_id': '3', 'name': 'c', 'mgr_id': '4'}, 
#  {'emp_id': '4', 'name': 'd', 'mgr_id': '1'}]

现在我们可以迭代查找管理器的名称。我们将使用next并提供一个生成器表达式来检查匹配的管理器ID。

>>> for entry in data:
...   mgr_id = entry['mgr_id']
...   mgr = next(e for e in data if e['emp_id'] == mgr_id)
...   print(f"{entry['name']} reports to {mgr['name']}")
...
a reports to b
b reports to d
c reports to d
d reports to a
for each in s.split(","):
employ_id, name, manager_id = each.split(":")
# do whatever with them

它所做的是创建一个列表,其中字符串的所有部分都用逗号分隔,出于速度原因,我将其压缩为列表理解,然后它将在每个项目上循环,在冒号上分割,并将变量employ_idnamemanager_id分配给值,然后您可以在for循环中对其进行处理。

相关内容

  • 没有找到相关文章

最新更新