البرمجة

تقسيم السلسلة إلى قاموس Python

To split a string and map each character into a dictionary in Python, you can use a dictionary comprehension along with the enumerate function. Here’s how you can do it:

python
# Original string original_string = 'value=sahi' # Split the string and map each character into a dictionary result = {index+1: char for index, char in enumerate(original_string)} # Print the result print(result)

This will output:

css
{1: 'v', 2: 'a', 3: 'l', 4: 'u', 5: 'e', 6: '=', 7: 's', 8: 'a', 9: 'h', 10: 'i'}

If you specifically want to skip the ‘=’ character and only map the characters after ‘=’, you can modify the code as follows:

python
# Original string original_string = 'value=sahi' # Split the string and map each character into a dictionary result = {index+1: char for index, char in enumerate(original_string.split('=')[-1])} # Print the result print(result)

This will output:

css
{1: 's', 2: 'a', 3: 'h', 4: 'i'}

This code splits the original string by ‘=’ and takes the last part (after ‘=’). It then maps each character of the remaining string to its index in a dictionary.

المزيد من المعلومات

بالتأكيد! يمكنك استخدام الدوال في Python لتحقيق هذا الهدف بطرق مختلفة. على سبيل المثال، يمكنك استخدام الدالة enumerate() للحصول على كل حرف في السلسلة مع موضعه الفعلي، ثم إنشاء قاموس لتخزين كل حرف مع موضعه. هناك أيضًا طريقة أخرى تستخدم دالة dict() مع enumerate() للحصول على نفس النتيجة. تفضل بمشاهدة الأمثلة التالية:

استخدام enumerate():

python
# السلسلة الأصلية original_string = 'value=sahi' # حلق على السلسلة وقم بإنشاء القاموس result = {index + 1: char for index, char in enumerate(original_string)} # طباعة النتيجة print(result)

استخدام dict() و enumerate():

python
# السلسلة الأصلية original_string = 'value=sahi' # إنشاء القاموس باستخدام dict() و enumerate() result = dict(enumerate(original_string, start=1)) # طباعة النتيجة print(result)

ستلاحظ أن النتيجة في الكودين السابقين ستكون {1: 'v', 2: 'a', 3: 'l', 4: 'u', 5: 'e', 6: '=', 7: 's', 8: 'a', 9: 'h', 10: 'i'}، حيث تتضمن جميع الحروف مع مواقعها في السلسلة الأصلية.

زر الذهاب إلى الأعلى