以下是一个示例代码,演示了如何按列对行进行索引,并在字符串中找到部分匹配:
# 创建一个二维列表,表示一个表格
table = [
['Name', 'Age', 'Country'],
['John', '28', 'USA'],
['Emily', '32', 'UK'],
['Mike', '45', 'Canada']
]
# 定义一个函数来按列对行进行索引
def index_table(table):
indexed_table = {}
for col in range(len(table[0])):
column_data = []
for row in range(1, len(table)):
column_data.append(table[row][col])
indexed_table[table[0][col]] = column_data
return indexed_table
# 调用函数进行索引
indexed_table = index_table(table)
print(indexed_table)
# 在字符串中查找部分匹配
search_string = 'John is from USA'
for key, value in indexed_table.items():
for item in value:
if item in search_string:
print(f'{item} is found in {key}')
输出结果为:
{'Name': ['John', 'Emily', 'Mike'], 'Age': ['28', '32', '45'], 'Country': ['USA', 'UK', 'Canada']}
John is found in Name
USA is found in Country