Get F-Curves of Selected Bones

Hello!
I’m trying to write a script that acts on only the F-Curves of selected bones. With my Armature selected, I can access the bones’ F-Curves like this, but how I can tell if the F-Curve’s associated bone is selected?

action = bpy.context.active_object.animation_data.action
fcurves = action.fcurves

I’m currently working with this code where I gather the names from selected_pose_bones and the armature’s fcurves and compare them, but it doesn’t seem very efficient to do two loops:

action = bpy.context.active_object.animation_data.action
sel_bone_names = list()

for pb in bpy.context.selected_pose_bones:
	sel_bone_names.append(pb.bone.name)

for fcurve in action.fcurves:
	tmp = fcurve.data_path.split("[", maxsplit=1)[1].split("]", maxsplit=1)
	bone_name = tmp[0][1:-1]
	if bone_name in sel_bone_names:
		print(fcurve.data_path)

Thank you!

Hi!

Fcurves are organized into so-called action groups. The name of an action group mirrors the data linked to the fcurve and can be accessed as a string in an fcurve’s group.name data path.

To get the pose bone of any fcurve:

fc = fcurves[0]
bone_name = fc.group.name

bone = bpy.context.object.pose.bones[bone_name]

Edit:
I just realized the question was the other way around - getting the fcurves of selected bones.
Grouped fcurves are, perhaps confusingly, found under group.channels property.

This prints the name of selected pose bones and their fcurves:

import bpy

bones = bpy.context.selected_pose_bones
action_groups = bpy.context.object.animation_data.action.groups

for bone in bones:
    group = action_groups.get(bone.name)
    if group is not None:
        print(bone.name, *group.channels, " ", sep="\n")